|
|
|
|
|
|
|
Analysis: A very simplified SimpleCat class is declared on lines 612. The constructor, copy constructor, and destructor all print an informative message so you can tell when they've been called. |
|
|
|
|
|
|
|
|
On line 34, main() prints out a message; you can see it on output line 1. On line 35, a SimpleCat object is instantiated. This causes the constructor to be called, and the output from the constructor is shown on output line 2. |
|
|
|
|
|
|
|
|
On line 36, main() reports that it is calling FunctionOne(), which creates output line 3. Because FunctionOne() is called passing the SimpleCat object by value, a copy of the SimpleCat object is made on the stack as an object local to the called function. This causes the copy constructor to be called, which creates output line 4. |
|
|
|
|
|
|
|
|
Program execution jumps to line 45 in the called function, which prints an informative message, output line 5. The function then returns, returning the SimpleCat object by value. This creates yet another copy of the object, calling the copy constructor and producing line 6. |
|
|
|
|
|
|
|
|
The return value from FunctionOne() is not assigned to any object, so the temporary object created for the return is thrown away, calling the destructor, which produces output line 7. Because FunctionOne() has ended, its local copy goes out of scope and is destroyed, calling the destructor and producing line 8. |
|
|
|
|
|
|
|
|
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 output line 10 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 Frisky goes out of scope, causing one final call to the destructor and printing output line 11. |
|
|
|
|
|
|
|
|
The net effect of this is that the call to FunctionOne(), because it passed the cat by value, produced two calls to the copy constructor and two to the destructor, although the call to FunctionTwo() produced none. |
|
|
|
|
|
|
|
|
Although passing a pointer to FunctionTwo() is more efficient, it is dangerous. FunctionTwo() is not allowed to change the SimpleCat object it is passed, yet it is given the address of the SimpleCat. This seriously exposes the object to change and defeats the protection offered in passing by value. |
|
|
|
|
|
|
|
|
Passing by value is like giving a museum a photograph of your masterpiece instead of the real thing. If vandals mark it up, there is no harm done to the original. Passing by reference is like sending your home address to the museum and inviting guests to come over and look at the real thing. |
|
|
|
|
|