7 Establishing the class invariant

 

This chapter covers

  • The class invariant, an essential view of what a class is and does
  • Building class behavior from a minimum set of essential functions
  • Treating classes as new data types
  • Good inheritance design, as seen from the class invariant
  • Ensuring classes work correctly and cooperate with the compiler

Classes represent data types. The C++ standardization committee could never anticipate every data type needed; therefore, the language was designed to be extensible. If a new data type is required, a developer can write it by creating a new class.

While writing a class is a simple process, writing a good class is much more challenging to get correct. Over the years, different advice has been given, and numerous problems have been detected. Learning some of these problems helps programmers detect these and similar problems in existing code. Eliminating these problems altogether guides a developer toward better class design.

7.1 Class invariants enforce proper class design

A class has a minimum of four essential characteristics. Some academics may suggest others, but these four should be regarded as fundamental:

  • Interpretation
  • Set of operations
  • Range of values
  • Memory mechanics

7.1.1 Interpretation

7.1.2 Set of operations

7.1.3 Range of values

7.1.4 Memory mechanics

7.1.5 Performance implications

7.2 Mistakes in class design

7.2.1 The class invariant

7.2.2 Establishing the class invariant

7.3 Mistake 44: Failing to maintain the class invariant

7.4 Mistake 45: Not thinking of classes as data types

7.5 Mistake 46: Not establishing a basis for methods

7.6 Mistake 47: Failing to code the big 3

7.7 Mistake 48: Using inheritance just for code reuse

7.8 Mistake 49: Overusing default constructors

7.9 Mistake 50: Failing to maintain the is-a relationship