100 C++ Mistakes and How to Avoid Them cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

3 Maintaining the Class Invariant

 

This chapter covers

  • Ways 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 assignment operator
  • The very common problem of failing to initialize variables of built-in types

After the hard work of establishing the class invariant discussed in the previous chapter, we must be careful to maintain it. Several aspects of program development provide opportunities for violating the invariant. We must become aware of some of these possibilities and be on guard to prevent their use.

The possibility of violating the class invariant exists 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 that a violation of the invariant can occur is when any state data changes. However, it is only sometimes obvious when this occurs. 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.

3.1 Maintaining the Class Invariant

3.2 Mistake #8 Writing Nonessential Accessors

3.3 Mistake #9 Providing Trivial Mutators

3.4 Mistake #10 Overusing Protected Instance Variables

3.5 Mistake #11 Mistaking Operator= and Copy Constructor Semantics

3.6 Mistake #12 Misunderstanding Shallow and Deep Copy Semantics

3.7 Mistake #13 Failing to Call Base Class Operators

3.8 Mistake #14 Failing to Use Virtual Destructors in Polymorphic Base Classes

3.9 Mistake #15 Calling Virtual Functions in Constructors and Destructors

3.10 Mistake #16 Attempting to Use Polymorphic Array Elements

3.11 Mistake #17 Failing to Initialize All Instance Variables

sitemap