Advertisement
Intermediate C++, Const Correctness

What is the mutable keyword?

Short answer

mutable allows a member variable to be modified even inside a const member function (or of a const object).

Save C++ mock interview
Advertisement
AModel answer
mutable allows a member variable to be modified even inside a const member function (or of a const object). It's used for members that don't affect the object's logical/observable state—caches, memoized values, mutexes, or usage counters—so a logically-const method can still update them.
struct Cache {
    int get() const { hits++; return value; } // hits is mutable
    mutable int hits = 0;
    int value = 0;
};
Real-world example
A cache's hit counter is mutable so read-only accessors can still increment it.
Likely follow-ups
  • When is mutable appropriate? | What is 'logical constness'?
Related topics