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;

	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.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: ";
	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 and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.