mutable
- C++ course
- Intermediate
- Lesson 27/116
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
// Define the Counter class here
int main() {
// Create a Counter instance, call get and print the result
return 0;
}Sample 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;
}Expected output
0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where can a mutable member be modified?
mutable int cacheHits;- Only inside const methods Correct answer
- Inside any method
- Only inside constructors
- It cannot be modified anywhere
Explanation: A mutable member can be modified even inside const methods.
2 Write the mutable keyword
private: ____ int cacheHits;
private: mutable int cacheHits;
Explanation: mutable allows modification inside a const method.
3 Match each keyword to its use
| Term | Meaning |
|---|---|
mutable |
Modifiable in const |
const |
Does not modify object |
private |
Class-only access |
mutable int cache |
Cache member |