Constant, Volatile and Static Function

What is the use of constant function, volatile function & static function (in programming & real life)? How do they differ from one another?

Questions by ketan712

Showing Answers 1 - 3 of 3 Answers

madi_czadi

  • Apr 1st, 2010
 

To understand what are const functions, we have to know and understand const objects. Let's say we have class:

class foo{
int x;
public:
foo(int arg): x(arg){}
int y;
};

In main function we write, so we create const object initialized with vaue 2:
 const foo f(2);
At this point we should ask oureslves what that means?
Well it means that, we tell compiler that this object will be constant, so none of it's component's during object live, will be changed. Well there are no problem for compiler with public members with that, all of them will become constant, let's say we can now write:

std::cout<<f.y;
but of course:
f.y=3;//This will cause an error
And now, if our class will look le't say like this:

class foo{
int x;
public:
foo(int arg): x(arg){}
void f(int arg){}
int y;
};

How to tell compiler suppose to know, if this function do not change the behavior of the object? Well it does not know, it doesn't matter if it changes it or not, so if we would like to call it, like this:

f.f(4);//This is error

We CAN'T INVOKE NON CONST FUNCTION INSIDE CONST OBJECT!!!
Of cousrse the solution is to change or add a const function, and of course at this point we should ask ourselves what is static function?
Well it informs compiler: Don't worry you can call me without any fears I wont change the behavior of the object, and the compiler is confident that he can call it.
Futhermore if we define the function const outside the class the const word must be repeated, becouse the compiler can treat it like other function, let's say:

class foo{
int x;
public:
foo(int arg): x(arg){}
void f(int arg){}
void f(int arg) const{}
int y;
};

void foo::f(int arg) const{......}//In definition static is repeated!

And now very important, if we have 2 functions with the same signature and we have const object, if we call f function:
f.f(9);//Const function will be called
On the other hand if our object won't be const the non static function would be called!
Futhermore, this is logic that const functions can call only other const functions and can't call non const functions, it can't change the behavior of the object. We should always use const function if it do not change the object behavior.
Next time I will write about static f.

Mateusz Wojtczak

The solution is ofcouse a const function.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions