Class Invariants

Learn about class invariants and its implementation.

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 postcondition has not been fulfilled. Similarly, a member function can always assume that the object is in a valid state when the function is called. The exception to this rule is the constructors and the destructor of a class. If we wanted to insert code to check that the class invariant holds true, we could do that at the following points:

Get hands-on with 1400+ tech skills courses.