How does const propagate with member objects and pointers (const propagation)?
Short answer
When an object is const, its non-mutable members are treated as const, so member functions called on them must be const.
Advertisement
AModel answer
When an object is const, its non-mutable members are treated as const, so member functions called on them must be const. However, if a member is a raw pointer, const only applies to the pointer itself, not the pointee—so a const method can still modify what a member pointer points to. std::experimental::propagate_const (or a wrapper) can extend constness to the pointee.
struct S {
int* p;
void f() const { *p = 5; } // allowed: pointee not const
};Real-world example
A const method unexpectedly mutates data via a member raw pointer because const doesn't propagate to the pointee.
Likely follow-ups
- Does const propagate through a member pointer? | What is propagate_const?
Related topics