Skip to content
UniCircle
EasyConceptualconst and references

const correctness: const member functions and mutable

Question CPP-LNG-006

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.

C++
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 marked const cannot 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::vector has both T& operator[](size_t) and const 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 *p and int *const p follow the same rules as in C. Read from right to left.
  • constexpr means "can be evaluated at compile time", which is a stronger idea than const.
  • const_cast can remove const, but modifying an object that was defined const is undefined behaviour.

Original UniCircle question. Last reviewed 22 Oct 2026.