mutable
keyword, which gives us more flexibility when working with const
objects.In the introductory course, we covered the const
keyword, and the importance of “const correctness”
One example is the ability to mark class methods as const
if they do not change any data members.
class Character {
public:
int GetHealth() const {
return Health;
}
private:
int Health{100};
};
This serves two purposes:
const
, or passing our object by reference to a function that hasn’t marked the parameter as const
However, there are some scenarios where we want some variables to be changeable by const methods.
Typically, these are private variables whose value has no noticeable, outward-facing effect. In the following example, we want to keep track of how many times our object’s Health
value was accessed:
class Character {
public:
int GetHealth() const {
++HealthRequests;
return Health;
}
private:
int Health{100};
int HealthRequests{0};
};
Naturally, the compiler won’t allow this:
'HealthRequests' cannot be modified because it
is being accessed through a const object
We could get around this simply by removing the const
specifier, but that’s not ideal.
const
is misleading to any code using our class. Whilst it is changing a data member, the variable it’s changing is completely inaccessible and has no visible effect. So, from the perspective of the outside world, the function really should be const
const
specifier has knock-on effects that can reverberate through our code base. For example, any code trying to call GetHealth
on a const reference to this object will now also throw errors.mutable
KeywordTo solve these problems, we have access to the mutable
 keyword.
Any data member marked as mutable
can be freely changed by const
 methods:
class Character {
public:
int GetHealth() const {
++HealthRequests;
return Health;
}
private:
int Health{100};
mutable int HealthRequests{0};
};
Naturally, to ensure our const
methods still mean something, mutable
should be used sparingly. It’s intended only for variables that, if changed, will not affect the object in any way that outside consumers will notice.
As such, the documentation aspect of const
methods should only have a subtle shift, from “this won’t change the object” to “this won’t change the object in any way you’ll care about”
— First Published
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.