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

/* sample.cpp */
#include <iostream>
using namespace std;

class Foo {
public:
	int a;
	Foo() {
		a = 4;
	}
};

int main() {
	const Foo foo_obj;
	foo_obj.a = 8;
	cout << foo_obj.a;
	return 0;
}

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.

#include <iostream>
using namespace std;

class Foo {
public:
	mutable int a;
	Foo() {
		a = 4;
	}
};

int main() {
	const Foo foo_obj;
	foo_obj.a = 8;
	cout << foo_obj.a;
	return 0;
}

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.
#include <iostream>
using namespace std;

class Foo {
public:
	mutable int a; // without mutable it will give error 
	Foo() {
		a = 4;
	}
	void setValue(int a) const;
};

void Foo::setValue(int a_) const
{
	this->a = a_; // modifying data a
}

int main() {
	Foo foo_obj;
	foo_obj.setValue(10);
	cout << foo_obj.a;
	return 0;
}

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?

Ref:

http://www.includehelp.com/cpp-tutorial/mutable-data-member.aspx



Related Contents to follow