To change the data members of the const
object the data members are declared as mutable in the class.
This is
shown in the following example:
#include <iostream.h>
class sample
{
private :
mutable int i;
public :
sample( int ii = 0 )
{
i = ii;
}
void fun( ) const
{
i++;
cout<< i;
}
};
void main( )
{
const sample s ( 15 ) ;
s.fun( );
}
Here, the object s is const and hence only const
functions can operate upon it. When the const function fun( )
gets called to operate upon object s, the data member i is
incremented. Ideally the data member should not be changed, as object is
defined const. But we can change the data member i because it is
declared as mutable in the class sample
No comments:
Post a Comment