What is const-correctness, and where can const be applied?
Const-correctness means marking everything that does not modify state as const, so the compiler enforces your intent. It documents the interface, prevents accidental modification, and enables optimisation.
Where it applies:
- Variables —
const int max = 100; - Function parameters —
void print(const std::string& s). Passing byconst&avoids a copy while promising not to modify. - Member functions —
int size() const;promises not to modify the object, and is required for the method to be callable on a const object. Omitting it is the most common const-correctness failure. - Return values — returning
const&to expose a member without allowing modification. - Pointers, in two distinct ways —
const char* pis a pointer to constant data (the data cannot change), whilechar* const pis a constant pointer (the pointer cannot be reseated).const char* const pis both. Read these right to left.
Note: Const-correctness is viral. If a low-level function is not const-correct, every caller is forced to give up const too, which is why it must be applied from the start — retrofitting it across a large codebase is genuinely painful. Also worth knowing: mutable exempts a member from const, which is legitimate for a cache or a mutex inside a const method.





