What does it mean for a class method to be marked as const? Can a const method modify any member variables?
Last updated
Marking a method const promises it won't modify the object's observable state, so it can be called on const objects and references. Inside it, this is a pointer to const, so member variables are read-only, with two deliberate exceptions.
What const enforces:
You cannot assign to non-
mutablemembers or call non-const methods from within it.It lets
constinstances be used and enables const-correct APIs.
Exceptions (yes, it can modify some members):
mutablemembers can be changed even in a const method (caches, mutexes, lazy-computed values).It only protects
this's direct members. If a member is a pointer, the pointee can still be modified (the pointer is const, not what it points to).
Const overloading: You can provide both a
constand non-constversion of a method; the compiler picks based on the object's constness.
[lang:cpp]
class Widget {
int value = 0;
mutable int cache = 0;
public:
int get() const { cache++; /* ok: mutable */ return value; }
// void set(int v) const { value = v; } // error: value not mutable
};