C++
mutable
Learn members that can change inside const with mutable.
mutable
Sometimes you need to modify a member inside a const method without changing the object's logical state. For example, a cache counter. In such cases you make the member mutable. A mutable member can be modified even inside a const method.
Example: class Query { private: mutable int cacheHits; public: int run() const { cacheHits++; return 42; } };. Here run is const; it does not change the object. But cacheHits is mutable, so it can be incremented. This enables side effects like performance tracking. The logical state stays the same while the implementation-level detail changes.
Caching use
The most common use of mutable is caching. If there is an expensive computation, you store the result and avoid recomputing. The computing method can be const, because the logical result does not change.
Example: class Config { private: mutable bool cached; mutable int cachedValue; public: int getValue() const { if (!cached) { cachedValue = 42; cached = true; } return cachedValue; } };. On the first call the value is computed and cached; on later calls it is returned from the cache. getValue is const but cached and cachedValue are mutable, so they can be modified. This provides transparent caching.
Exercise Add a mutable member to the Counter class
Define a Counter class. Under private: add int value; and mutable int reads;. Under public: add the constructor Counter() { value = 0; reads = 0; } and the method int get() const { reads++; return value; }. In main create an instance, call get() twice and print the result of the second get() with std::cout.
Show example solution
#include <iostream>
class Counter {
int value;
mutable int reads;
public:
Counter() {
value = 0;
reads = 0;
}
int get() const {
reads++;
return value;
}
};
int main() {
Counter c;
c.get();
std::cout << c.get();
return 0;
}
Test yourself
-
Where can a mutable member be modified?
mutable int cacheHits;
- Only inside const methods
- Inside any method
- Only inside constructors
- It cannot be modified anywhere
Show answer
Only inside const methods — A mutable member can be modified even inside const methods.
-
Write the mutable keyword
private: ____ int cacheHits;
Show answer
private: mutable int cacheHits;
-
Match each keyword to its use
- mutable
- Modifiable in const
- const
- Does not modify object
- private
- Class-only access
- mutable int cache
- Cache member
Next lesson: friend