C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Mutable data member in C++ programming language

Learn: What is Mutable Data member in C++, how to define it? Class example with mutable data member in C++ programming language

Mutable data member is that member which can always be changed; even if the object is const type. It is just opposite to “const”. Sometime we required to use only one or two data member as a variable and other as a constant. In that situation, mutable is very helpful to manage classes.

To make data member as a mutable, we need to use mutable keyword. It is in-built in C++ language.

Example of Mutable data member in C++

#include <iostream>
using namespace std;

class Sample
{
	int x;
	mutable int y;

	public:
	Sample(int a=0, int b=0)
	{ x=a; y=b;}

	//function to set value of x
	void setx(int a=0)
	{x = a;}

	//function to set value of y
	//value of y being changed, even if member function is constant.
	void sety(int b=0) const
	{y = b;}


	//function to display x and y.
	//this has to be const type, if member function is constant type.
	void display() const
	{
		cout<<endl<<"x: "<<x<<" y: "<<y<<endl;
	}
};

int main()
{
	const Sample s(10,20); // A const object

	cout<<endl <<"Value before change: ";
	s.display();

	s.setx(100);  //Error: x can not be changed, because object is constant.
	s.sety(200);  //y still can be changed, because y is mutable.

	cout<<endl<<"Value after change: ";
	s.display();
	
	return 0;
}

In this program, statement s.setx(100); will produce an error but statement s.sety(200); will not.

Thus, it is cleared that we can change only the value of y (because of mutable) and we cannot change the value of x.









COMMENTS