
Constant and Classes
A class object defined with the const keyword can invoke only those member functions that are also defined with const. It makes it possible to overload a const-member function with a non-const member function that defines the same prototype. If programmer attempts to call a member function with an object that is not defined as const, the call results in non-const function.
For example,
class A
{
private :
int * ptr ;
public :
void set ( int n ) const
{
* ptr = n ; // ok
ptr = &n ; //error
}
void set ( int n )
{
ptr = &n ; // ok
}
} ;
Here, set ( int n ) const is a permissible const member function because it does not modify the value of ptr --- rather, it changes the value of the object addressed by ptr.
In this case const-ness of the class object determines which of the functions is invoked:
int main ( )
{
int v = 15 ;
A obj1;
const A obj2 = obj1 ; // initialization
obj1.set ( v ) ; // non-const member function
obj2.set ( v ) ; // const member function
}
If the non-const member function is not declared, const function will invoke even for a non-const object.
How to Cast-Away const?
The const_cast operator can be used to remove the const modifier from a type. Here is an example that removes the const-ness from a const function:
class A
{
private :
count ;
public :
A ( int n ) ;
void set ( ) const
{
count ++ ; // error
const_cast <A *> ( this ) ->count ++ ; //ok
}
};
mutable Members
The keyword mutable can be used in declarations of a class members. It allows certain members of constant objects to be modified in spite of const-ness. It also means that a const function can modify a mutable class member.
For example,
class A
{
public :
int m ;
mutable int n ;
A ( ) : m ( 9 ) , n ( 34 )
{ }
int GetValue ( ) const
{
n = 0 ; // ok n is mutable
return m ;
}
} ;
int main ( )
{
const A a ;
a.m = 0 ; // error
a.n = 0 ; // ok
}