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.