Class Invariants
Learn about class invariants and its implementation.
We'll cover the following...
Class invariants
As mentioned in the previous section, a class invariant defines the valid states of an object. It specifies the relationship between the data members inside a class. An object can temporarily be in an invalid state during the time a member function is being executed. The important thing is that the invariant is upheld whenever the function passes the control to some other code that can observe the state of the object. This can happen when the function:
Returns
Throws an exception
Invokes a callback function
Calls some other function that might observe the state of the currently calling object; a common scenario is when passing a reference to this to some other function
It's important to realize that the class invariant is an implicit part of the precondition and postcondition for every member function of a class. If a member function leaves an object in an invalid state, the ...