Listing 9.10 creates the SimpleCatobject and then calls two functions. The first
function receives the Catby value and then returns it by value. The second one
receives a pointer to the object, rather than the object itself, and returns a pointer to the
object.
The very simplified SimpleCatclass is declared on lines 6–12. The constructor, copy
constructor, and destructor all print an informative message so that you can tell when
they’ve been called.
On line 34,main()prints out a message, and that is seen on the first line of the output.
On line 35, a SimpleCatobject is instantiated. This causes the constructor to be called,
and the output from the constructor is seen on the second line of output.
On line 36,main()reports that it is calling FunctionOne, which creates the third line of
output. Because FunctionOne()is called passing the SimpleCatobject by value, a copy
of the SimpleCatobject is made on the stack as an object local to the called function.
This causes the copy constructor to be called, which creates the fourth line of output.
Program execution jumps to line 46 in the called function, which prints an informative
message, the fifth line of output. The function then returns, and returns the SimpleCat
object by value. This creates yet another copy of the object, calling the copy constructor
and producing the sixth line of output.
The return value from FunctionOne()is not assigned to any object, and so the temporary
object created for the return is thrown away, calling the destructor, which produces the
seventh line of output. Because FunctionOne()has ended, its local copy goes out of
scope and is destroyed, calling the destructor and producing the eighth line of output.
Program execution returns to main(), and FunctionTwo()is called, but the parameter is
passed by reference. No copy is produced, so there’s no output. FunctionTwo()prints
the message that appears as the tenth line of output and then returns the SimpleCat
object, again by reference, and so again produces no calls to the constructor or
destructor.
Finally, the program ends and Friskygoes out of scope, causing one final call to the
destructor and printing the final line of output.
The net effect of this is that the call to FunctionOne(), because it passed the Friskyby
value, produced two calls to the copy constructor and two to the destructor, while the call
to FunctionTwo()produced none.
Passing a constPointer ..................................................................................
Although passing a pointer to FunctionTwo()is more efficient, it is dangerous.
FunctionTwo()is not meant to be allowed to change the SimpleCatobject it is passed,
274 Day 9
ANALYSIS