cpp core · high

Const-Correctness

Const-correctness is a compile-time contract. A const member function promises not to modify the object, and a const object (or const reference) may call only const methods — calling a non-const method on it is ill-formed because it discards the qualifier. Members marked mutable are the exception: they may change inside a const method to support logical const (caches, counters, mutexes). With pointers, read the type right-to-left: 'const int*' is a pointer to const data, 'int* const' is a const pointer to mutable data. Default to const everywhere it applies and let the compiler enforce intent.

🔑 Key line

A const member function promises not to modify the object, so a const object or const reference can call only const methods — mark everything that doesn't mutate const; mutable members stay writable for logical-const state like caches.

The code

class Widget {
int v_;
mutable int reads_ = 0; // mutable: writable even in a const method
public:
int get() const {
++reads_;
return v_;
} // const: won't modify *this
void set(int x) {
v_ = x;
} // non-const: may modify
};
const Widget w; // const object
Widget m; // non-const object
w.get(); // OK - const object may call const methods
w.set(3); // ERROR - discards the 'const' qualifier
m.get();
m.set(3); // OK - non-const object may call anything
const int* p = &n; // pointer to const int : *p read-only, p can repoint
int* const q = &n; // const pointer to int : *q writable, q is fixed
const int* const r = &n; // both fixed

What this lesson walks through

  1. 01const is a promise
  2. 02const object -> const method: OK
  3. 03const object -> non-const method: error
  4. 04non-const object: full access
  5. 05mutable: logical const
  6. 06const with pointers: read right-to-left
  7. 07Be const by default

Marking a member function const is a promise to the compiler: this call will not modify the object. The flip side: a const object (or const reference) may call only const member functions.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Const-Correctness and 100+ animated C++ interview lessons.

← Previous
Lambda Captures: [=] vs [&]
Next →
The Spaceship Operator <=>