Contents Up << >>

What do I do if I want to update an "invisible" data member inside a "const" member function?

Use "mutable", or use "const_cast".

A small percentage of inspectors need to make innocuous changes to data members (e.g., a "Set" object might want to cache its last lookup in hopes of improving the performance of its next lookup). By saying the changes are "innocuous," I mean that the changes wouldn't be visible from outside the object's interface (otherwise the method would be a mutator rather than an inspector).

When this happens, the data member which will be modified should be marked as "mutable" (put the "mutable" keyword just before the data member's declaration; i.e., in the same place where you could put "const"). This tells the compiler that the data member is allowed to change during a const member function. If you can't use "mutable", you can cast away the constness of "this" via "const_cast". E.g., in "Set::lookup() const", you might say,

Set* self = const_cast<Set*>(this);

After this line, "self" will have the same bits as "this" (e.g., "self==this"), but "self" is a "Set*" rather than a "const Set*". Therefore you can use "self" to modify the object pointed to by "this".