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.






Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




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 (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.