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.
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 methodpublic: 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 objectWidget m; // non-const object
w.get(); // OK - const object may call const methodsw.set(3); // ERROR - discards the 'const' qualifierm.get();m.set(3); // OK - non-const object may call anything
const int* p = &n; // pointer to const int : *p read-only, p can repointint* const q = &n; // const pointer to int : *q writable, q is fixedconst int* const r = &n; // both fixedWhat this lesson walks through
- 01const is a promise
- 02const object -> const method: OK
- 03const object -> non-const method: error
- 04non-const object: full access
- 05mutable: logical const
- 06const with pointers: read right-to-left
- 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.