What does const after a member function signature mean, as in int size() const;? Why does const-correctness matter, and what is mutable for?
Show the explanation
`const` after the parameter list promises that the function does not modify the object's observable state. Inside it, this has type const T*, so assigning to a member or calling a non-const member function is a compile error.
class Account {
double balance = 0;
public:
double getBalance() const { return balance; } // read-only: callable on const objects
void deposit(double x) { balance += x; } // modifies: not const
};
void report(const Account &a) {
a.getBalance(); // OK
a.deposit(5); // error: deposit() is not const
}Why it matters
- const objects and const references can only call const member functions. Code everywhere passes
const T&to avoid copies, so a getter that is not markedconstcannot be called through such references. This is the usual reason "my getter doesn't compile" in interviews. - It documents intent and lets the compiler catch accidental changes.
- You can overload on const.
std::vectorhas bothT& operator[](size_t)andconst T& operator[](size_t) const, so a const vector hands out read-only access.
`mutable` marks a member that may change even inside const functions. It is for state that is not part of the object's logical value: a cached result, a lazily computed hash, a std::mutex locked inside a const getter, or a debug counter.
Related
const int *pandint *const pfollow the same rules as in C. Read from right to left.constexprmeans "can be evaluated at compile time", which is a stronger idea thanconst.const_castcan remove const, but modifying an object that was defined const is undefined behaviour.
Original UniCircle question. Last reviewed 22 Oct 2026.
