The mutable keyword in C++ before any data member of a class allows constant functions to modify it.

You know that inside a const member function in c++ , a class member variable cannot be changed.

For example,

In the below class, if you try to modify the carID variable inside the const function “int getId() const“, the compiler will flash an error on the compile time itself.

class Car
{
	int carID;

public:
	Car():carID(123)//initialize car id
	{
	}

	//const function.
	//this function cannot change any data member
	//of the class.
	int getId()const
	{
		this->carID = 456;// Error cannot modify data
		return this->carID;
	}
};

So, if you want to allow modification of a class member variable in a constant function, you’ve to use mutable keyword before the class variable.

See the below mutable example in C++ code.

The function “int getId() const” can modify the carID variable.

class Car
{
	mutable int carID;

public:
	Car():carID(123)//initialize car id
	{	

	}

	int getId()const
	{
		this->carID = 456;//OK, data can be modified.
		return this->carID;
	}
};
int main(){

	Car c;
	cout<<"Car ID ="<< c.getId();

}

Output:456

Conclusion

The importance of mutable keyword in C++ is, when you want a class member variable to be modified within a constant function, then use mutable keyword before the class variable.

Related Posts