In this blog post we are going to learn basic of mutable keyword in c++. Let us see a very basic example code:

When an object is declared or created using the const keyword, its data members can never be changed, during the object’s lifetime. In this way const Foo foo_obj; ,foo_obj is a const object and its data members cannot be changed.

Try to compile sample.cpp

#g++ sample.cpp

../main.cpp: In function ‘int main()’:

../main.cpp:14:12: error: assignment of member ‘Foo::a’ in read-only object

foo_obj.a = 8;


So , we cannot modify Foo class data member a as we have declared Foo class object foo_obj as const. So how can you modify const class member data or variable ?

The keyword mutable is used to allow a particular data member of const object to be modified. So now let us modify sample.cpp file as below.

Now the sample.cpp can be compiled and run successfully because data member a is declared mutable as mutable int a;

  • mutable members can be modified inside const member functions.

Interview Questions on mutable keyword

  • What is importance of mutable keyword in c++?
  • What is use of mutable keyword in c++ explain with a real example?


Related Contents to follow