Search⌘ K
AI Features

Class Invariants

Explore how class invariants define valid states within C++ objects and ensure reliable code by maintaining these invariants. Understand the role of asserts and contract management in detecting violations, and learn best practices for designing safer, cohesive classes that are easier to maintain and debug.

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 ...