The program of Figs. 9.7–9.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 defines object first
(line 10) in global scope. Its constructor is actually called before any statements in main
execute and its destructor is called at program termination after the destructors for all objects with automatic storage duration have run.
Function main
(lines 12–23) declares three objects. Objects second
(line 15) and fourth
(line 21) are local objects, and object third
(line 16) is a static
local object. The constructor for each of these objects is called when execution reaches the point where that object is declared. The destructors for objects fourth
then second
are called—in the reverse of the order in which their constructors were called—when execution reaches the end of main
. Because object third
is static
, it exists until program termination. The destructor for object third
is called before the destructor for global object first
, but after all other objects are destroyed.
Function create
(lines 26–33) declares three objects—fifth
(line 29) and seventh
(line 31) as local automatic objects, and sixth
(line 30) as a static
local object. The destructors for objects seventh
then fifth
are called—the reverse of the order in which their constructors were called—when create
terminates. Because sixth
is static
, it exists until program termination. The destructor for sixth
is called before the destructors for third
and first
, but after all other objects are destroyed.