Sams Teach Yourself C++ in 21 Days

(singke) #1
15: [0] 0
16: [1] 1
17: [2] 2
18:
19: animal array...
20: [0] 0
21: [1] 10
22: [2] 20
23:
24: Destroyed an animal...
25: Destroyed an animal...
26: Destroyed an animal...
Listing 19.6 reproduces both classes in their entirety so that you can see the cre-
ation and destruction of temporary Animalobjects. The value of DefaultSize
has been reduced from 10 to 3 to simplify the output.
The Animalconstructors and destructors on lines 33–48 each print a statement indicating
that they are called.
On lines 75–82, the template behavior of an Arrayconstructor is declared. On lines
116–120, the specialized constructor for an Arrayof Animals is demonstrated. Note that
in this special constructor, the default constructor is allowed to set the initial value for
each Animal, and no explicit assignment is done.
The first time this program is run, the first set of output is shown. Line 1 of the output
shows the three default constructors called by creating the array. The user enters four
numbers for the array, and these are entered into the integer array.
Execution jumps to AnimalFillFunction(). Here, a temporary Animalobject is created
on the heap on line 163, and its value is used to modify the Animalobject in the array on
line 164. On line 165, the temporary Animalis destroyed. This is repeated for each mem-
ber of the array and is reflected in the output on line 6.
At the end of the program, the arrays are destroyed, and when their destructors are
called, all their objects are destroyed as well. This is reflected in the output on line 16.
For the second set of output, the special implementation of the array of character con-
structor, shown on lines 116–120 of the program, is commented out. When the program
is run again, the template constructor, shown on lines 75–82 of the program, is run when
the Animalarray is constructed. This causes temporary Animalobjects to be called for
each member of the array on lines 80 and 81 of the program, and is reflected in the sec-
ond set of output on lines 1–3.
In all other respects, the output for the two runs is identical, as you would expect.

688 Day 19


ANALYSIS
Free download pdf