8 Maintaining the class invariant

 

This chapter covers

  • How to ensure that the class invariant is maintained in program design
  • Difficulties that arise from indiscriminate use of older object-oriented design advice
  • The distinctions between copy constructors and the copy assignment operator
  • The widespread problem of failing to initialize variables of built-in types

After the finishing the hard work of establishing the class invariant discussed in chapter 7, developers must be careful to maintain it. Several aspects of program development provide opportunities for violating the invariant. It’s important to become aware of some of these possibilities and be on guard to prevent their use.

There is a possibility of violating the class invariant whenever data is used to initialize or modify a state variable. The flexibility and fine granularity of C++ constructs provide ample opportunity for affecting the data, sometimes in surprising ways. The most obvious place a violation of the invariant can occur is when any state data changes. However, it is only sometimes obvious when this happens. The construction and deletion of objects is a veiled process to some degree yet plays an essential role in establishing the content—hence, the invariance—of an object.

8.1 Maintaining the class invariant

8.2 Mistake 51: Writing nonessential accessors

8.3 Mistake 52: Providing trivial mutators

8.4 Mistake 53: Overusing protected instance variables

8.5 Mistake 54: Mistaking operator= and copy constructor semantics

8.6 Mistake 55: Misunderstanding shallow and deep copy semantics

8.7 Mistake 56: Failing to call base class operators

8.8 Mistake 57: Failing to use virtual destructors in polymorphic base classes

8.9 Mistake 58: Calling virtual functions in constructors and destructors

8.10 Mistake 59: Attempting to use polymorphic array elements

8.11 Mistake 60: Failing to initialize all instance variables