Sobes.tech
Junior — Middle

How can the state be modified inside a method declared as const?

sobes.tech AI

Answer from AI

In C++, a method declared as const (with the const keyword) cannot modify the state of the object, meaning it cannot change non-static class fields. However, there is a way to modify the state within such a method — by using the mutable keyword for class fields. Fields declared as mutable can be modified even inside const methods.

Example:

class Example {
    mutable int counter = 0; // can be modified in const methods
public:
    void foo() const {
        counter++; // modifying mutable field inside const method
    }
};

Thus, mutable allows storing mutable state, for example, for caching or counting calls, without violating the constness of the interface.