C++ const correctness in OOP
const helps separate functions that only read an object from functions that
modify an object.
In OOP, this belongs mostly to encapsulation.
The class should make it clear:
- which functions change object state
- which functions only read object state
Const member function
const after a member function means:
this function promises not to modify the object.
This function can modify the object:
This function only reads the object:
Const object can only call const methods
If an object is const, C++ only allows calling const member functions.
The object is read-only, so only read-only functions are allowed.
Pass object by const reference
Use const T& when a function only needs to read an object.
This avoids copying the object and protects it from modification.
Important:
Because dog is const Dog&, the function can only call const methods.
Getters should usually be const
A getter usually reads object state, so it should be const.
This means you can use the getter even when the object is const.
Returning const std::string& also prevents outside code from modifying the
private member through the returned reference.
Const and overloads
Sometimes a class provides two versions of the same function:
- one for non-const objects
- one for const objects
Usage:
This pattern is common in containers and classes that expose controlled access.
Const and virtual functions
When overriding a virtual function, const must match.
This is correct:
This is not the same function:
The const is part of the member function signature.
Mutable
mutable allows a member to change even inside a const member function.
Use it rarely.
One common use is debug counters or cached values.
Even though call_count() is const, it can change call_count_ because that
member is marked mutable.
This should not be used to hide normal object modification.
Quick rules
| Situation | Use |
|---|---|
| Method only reads object state | add const after the function |
| Method modifies object state | do not add trailing const |
| Function receives object only for reading | pass const T& |
| Getter reads state | make getter const |
| Return internal object by reference | prefer const T& from const getter |
| Override virtual const function | derived function must also be const |
| Need cache/debug counter in const function | consider mutable, carefully |
Simple rule
If a member function only reads the object, write it like this:
If it changes the object, write it like this: