Mutable data members
When we create a constant object,
none of its data members can be changed. In a rare situation, however, you may
want some data members should be allowed to change despite the object being
const.
1.
Mutable data members can be modified inside constant
member functions also.
2.
Prefixing the declaration of a data member with the
keyword mutable makes it a mutable
data member.
The following example makes the
use of mutable keyword clear.
EXAMPLE:
class A
{
int x;
mutable int y;
public:
void abc ()
const
{
x++; // Error. Since abc () is a constant function
and x is not a mutable
member.
y++; // No error. Since y is declared as mutable
it is allowed to be
changed even in constant member
functions.
}
void def ()
{
x++; // No error. Since def () is a non constant
member function, x can be
changed.
y++; // No error. Since def () is a non constant
member function, x can be
changed.
}
};
It is important to understand
that a mutable data member can never be a constant.
No comments:
Post a Comment