Click to See Complete Forum and Search --> : [RESOLVED] Mutable variable


sapatchay
April 7th, 2006, 03:57 AM
When we declare the variable as mutable; it says that we want to change the value of that variable in middle of the program. So what it signifies rather if we declare a simple any variable then it also can be modify in the program\
Dose it having any spacial meaning?

wildfrog
April 7th, 2006, 04:05 AM
Hmm, are you mixing mutable with the volatile keyword?

A mutable variable is a variable that can be modified from a constant member function:
class yourClass
{
protected:
mutable int a;

public:
void func() const
{
a++; // function is const, but we can modify this->a
}
};

- petter

sapatchay
April 7th, 2006, 04:17 AM
Got it.......
A variable can not be modified using the cosnt member function but mutable varibale can be changed using the const member function.

Thanks WildFrog

Graham
April 7th, 2006, 09:59 AM
Got it.......
A variable can not be modified using the cosnt member function but mutable varibale can be changed using the const member function.

Thanks WildFrog
Yep. But don't let that tempt you into doing bad things. Consider that a const member function is promising that it will not change the observable state of the object. That is, a user of your class should be confident that - as far as he is concerned - calling the function leaves the object unchanged. So, mutable is useful in situations where you have some "housekeeping" data that doesn't affect the observable state of the object, but which may need to be modified in a const function.

One example of this may be that (for unexplained reasons) you want to count how often the function is called: this is irrelevant to your users, and does not affect them, so making the count a mutable member is quite permissable.

What is definitely not OK, though, is to use it to get around a const function because your design is poor, for example.