On Day 5, you learned that these objects are copied onto the stack. Doing so takes time
and memory. For small objects, such as the built-in integer values, this is a trivial cost.
However, with larger, user-created objects, the cost is greater. The size of a user-created
object on the stack is the sum of each of its member variables. These, in turn, can each
be user-created objects, and passing such a massive structure by copying it onto the stack
can be very expensive in performance and memory consumption.
Another cost occurs as well. With the classes you create, each of these temporary copies
is created when the compiler calls a special constructor: the copy constructor. Tomorrow,
you will learn how copy constructors work and how you can make your own, but for
now it is enough to know that the copy constructor is called each time a temporary copy
of the object is put on the stack.
When the temporary object is destroyed, which happens when the function returns, the
object’s destructor is called. If an object is returned by the function by value, a copy of
that object must be made and destroyed as well.
With large objects, these constructor and destructor calls can be expensive in speed and
use of memory. To illustrate this idea, Listing 9.10 creates a stripped-down, user-created
object:SimpleCat. A real object would be larger and more expensive, but this is suffi-
cient to show how often the copy constructor and destructor are called.
LISTING9.10 Passing Objects by Reference
1: //Listing 9.10 - Passing pointers to objects
2:
3: #include <iostream>
4:
5: using namespace std;
6: class SimpleCat
7: {
8: public:
9: SimpleCat (); // constructor
10: SimpleCat(SimpleCat&); // copy constructor
11: ~SimpleCat(); // destructor
12: };
13:
14: SimpleCat::SimpleCat()
15: {
16: cout << “Simple Cat Constructor...” << endl;
17: }
18:
19: SimpleCat::SimpleCat(SimpleCat&)
20: {
21: cout << “Simple Cat Copy Constructor...” << endl;
272 Day 9