Junior — Middle
What is the purpose of the mutable keyword inside a method declared as const?
sobes.tech AI
Answer from AI
The keyword mutable in C++ allows modifying the data member of an object even inside a const method. Usually, a const method cannot change the state of an object, but there are cases when it is necessary to store mutable data that does not affect the logical constancy of the object, such as a cache or an access counter.
Example:
class Example {
mutable int cache;
public:
Example() : cache(0) {}
int getValue() const {
// Can modify cache despite being const
cache++;
return cache;
}
};
Here, cache can be modified inside getValue() const because it is declared as mutable.