chapter seven

7 Establishing the Class Invariant

 

This chapter covers

  • The class invariant, an essential view of what a class is and what it 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 that 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. Eliminating these problems guides a developer into a better class design. Learning some of these problems will help the programmer detect these and similar issues in existing code.

7.1 A Class Invariant Enforces Proper Class Design

A class has at minimum four characteristics that are essential to consider; some academics might suggest more, but these four should be regarded as the minimum:

  • 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 Three

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