Saturday, 2 October 2010

Constant member functions



Constant member functions ( ‘const’ keyword)

1.      Constant member functions are member functions which prevent to change the value of data members within the scope of the member functions.
2.      Constant member functions are specified as constants by suffixing the prototype and the function definition with the keyword const.
3.      Normally const is used in two cases:
a)      On normal variables to prevent them from being modified.
b)      On function arguments to keep a function from modifying a variable passed to it by value or by reference.

EXAMPLE:

#include<iostream.h>
class sample
{
private:
int data;
public:
fun1()
{
data=0;
}

void fun2 ()
{
data=10;
}

void fun3 () const       //Constant Member Function
{
data=20;          //Error since fun3 is a constant member 
                        //function it should not try to modify data.
}

void show data ()
{
cout<<”endl<<”data=”<<data;
}
};

Ø  Note that to make fun3() constant keyword const is placed after the declaration but before the function body. If the function declared inside the class but defined outside it then it is necessary to use const in declaration as well as in definition.
Ø  Which member functions should be made constant? - Member functions that do nothing but only acquire data from an object are obvious candidates for being made const.
If a const is placed inside a function its effect would be localized to that function only, whereas, if it is placed outside of all functions then its effect would be global.

No comments:

Post a Comment