Showing posts with label Mutable. Show all posts
Showing posts with label Mutable. Show all posts

How do I change a data member of the const object?

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

C++: Mutable Keyword

When we create a const object none of its data members can change.In a rare situation,however,you may want some data member should be allowed to change despite the object being const.

This can be achieved by the mutable keyword.This is shown in the following example:
#include<iostream.h>
class sample
{
           private: 
                       mutable int i;
           public:
                       sample(int x=0)
                       {
                              i=x;
                       }
                       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 on it.When the const function fun() gets called to operate on object s,the data member i is incremented.Ideally the data member should not be changed,as object is defined as const.But we can change the data member i because it is declared as mutable in the call sample.