What does it mean: Object’s observable state?
I was reading yesterday in “Exceptional C++” Solution to item 43 and there is a fragment:
private:
void InvalidateArea() { area = -1; }
Even though this function modifies the object’s internal state, it should be const. Why? Because this function does not modify the object’s observable state. We are doing some caching here, but that’s an internal implementation detail and the object is logically const even if it isn’t physically const.
Corollary: The member variable area should be declared mutable. If your compiler doesn’t support mutable yet, kludge this with a const_cast of area_ and write a comment telling the next person to remove the const_cast once mutable is available—but do make the function const._
As usual thanks for answers.
In this context, “observable state” means whether something is, directly or indirectly, visible to users of the object.
If using code can not, through observing the return value of any accessible member function or the value of any accessible data member, tell a difference between the object having one value of
areaor another, thanareais not part of the object’s observable state.If, OTOH, using code could, for example, call a member function, and that function’s result would differ depending on the value of
area, thenareawould be part of the object’s observable state.