Monday, March 5, 2012

What is mutable variable in C++??

There are some cases where data members are declaring as const, and later want to change the value of the const variable.In C++, it is not legal to change the const value, by using mutable it is possible. This keyword can be applied to only non-static and non-constant data members.

Example for changing constant object data member:

class mute{

public:
int x ;
mutable int y;  // mutable variable declaration
mute() // constructor
{
x=10;
y=10;

}
};
int main()
{
const mute m; // constant object
//m.x=20; // Illegal cant change the data members in a constant object
m.y=20; // Legal, we can change , because its a mutable
}
For the above sampel code, there is class mute with one int and one mutable int data member functions. There is constant object for the class. If you try to modify the normal data members here it is x in line no.16, we will get compilation error. But we can modify the mutable  data , here it is y in line no.17.

Example for changing the constant function data:
class mute{

public:
int x ;
mutable int y;
mute()
{
x=10;
y=10;

}
void setValue(int a) const
{
//x=a; // Illegal, cant change the values in constant function
y=a; // legal, mutable data allowed to change in constant functions
}
};
int main()
{
mute m;
m.setValue(5);
}

In the above sample code, where we are changin the data members using constant functions. In line no.14, if you try to change the normal variable in constant function it will throuh an error. But if you see in line no.15 , its perfectly legal to change the mutable varaible in constant function.

1 comment:

Saharsh Jain said...

mutable so nycly illustrated thnx buddy for sharing this

Popular Posts