Demonstrating When Constructors and Destructors Are Called

The program of Figs. 9.79.9 demonstrates the order in which constructors and destructors are called for objects of class CreateAndDestroy (Fig. 9.7 and Fig. 9.8) of various storage classes in several scopes. Each object of class CreateAndDestroy contains an integer (objectID) and a string (message) that are used in the program’s output to identify the object (Fig. 9.7, lines 16–17). This mechanical example is purely for pedagogic purposes. For this reason, line 19 of the destructor in Fig. 9.8 determines whether the object being destroyed has an objectID value 1 or 6 (line 19) and, if so, outputs a newline character. This line makes the program’s output easier to follow.

Figure 9.9

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.