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:
class sample
                       mutable int i;
                       sample(int x=0)
                       void fun() const
void main()
          const sample s(15);

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.

No comments:

Post a Comment