Chapter 2 - Constructors, Destructors, and Assignment Operators

Almost every class you write will have one or more constructors, a destructor, and a copy assignment operator. Little wonder. These are your bread-and-butter functions, the ones that control the fundamental operations of bringing a new object into existence and making sure it’s initialized, getting rid of an object and making sure it’s properly cleaned up, and giving an object a new value. Making mistakes in these functions will lead to far-reaching — and unpleasant — repercussions throughout your classes, so it’s vital that you get them right. In this chapter, I offer guidance on putting together the functions that comprise the backbone of well-formed classes.

Item 5:arrow-up-right Know what functions C++ silently writes a calls.

Item 6:arrow-up-right Explicitly disallow the use of compiler-generated functions you do not want.

Item 7:arrow-up-right Declare destructors virtual in polymorphic base classes.

Item 8:arrow-up-right Prevent exceptions from leaving destructors.

Item 9:arrow-up-right Never call virtual functions during construction or destruction.

Item 10:arrow-up-right Have assignment operators return a reference to *this.

Item 11:arrow-up-right Handle assignment to self in operator=.

Item 12:arrow-up-right Copy all parts of an object.

Last updated