What exactly does the keyword 'mutable' mean? It seems that both const and non-const functions can be called on mutable members. But that seems to defeat the very purpose of const...
mutable
Collapse
X
-
Mutable means to be able to "change" the value.
A const method can access a mutable value and use the value, but a const method can not change that value. Only non-const methods can change a value
BTW: This better not be some exam question. You have been around here long enough to know that you are not suppose to post those questions. -
mutable means that the member can be changed even if the object is const.
Like a linked list node:
[code=cpp]
class Node
{
Data* theData;
Node* prev;
Node* next;
};
[/code]
If the Node object is const, you can't change the next/prev pointers. That means you can't have linked list of const Node objects. To avoid this, tou make the next/prev members mutable. It's your way of saying that the nest/prev members are not part of the "const-ness" of the object:
[code=cpp]
class Node
{
Data* theData;
mutable Node* prev; //OK to change using a const object
mutable Node* next;
};
[/code]
Of course, you can abuse this but if you play ball using the rules, this is a pretty good way to do things.Comment
Comment