Advanced C++: Mutable Member

Home / Advanced C++: Mutable Member

Advanced C++: Mutable Member

December 3, 2015 | Article | No Comments

In the previous article we have discussed a const member function. A const member function is a mechanism for function to prevent it to modify a data.

In practical, const functions is needed to keep purity of class. A non privileged function is restricted to modify member variable. But sometimes we are forced to change data from const function (well, it’s so rare). To do so, we have to declare data as mutable member.

This simple code will tell us about keyword mutable:

#include <iostream>
using namespace std;

class Example {
	mutable int x;
	void setX(int value) const {
		x = value;		// correct
	int getX() const {
		return x;		// correct

int main() {
	Example* p;

	p = new Example;
	cout<<"The x has value "<<p->x<<endl;

	return 0;

In this example, function setX() is allowed to modify x because x is declared as mutable.


About Author

about author


A man who is obsessed to low level technology.

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Share Buttons and Icons powered by Ultimatelysocial