< previous page page_178 next page >

Page 178
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. Passing such a massive structure by copying it onto the stack can be very expensive in terms of performance and memory consumption.
There is another cost as well. With the classes you create, each of these temporary copies is created when the compiler calls a special constructor: the copy constructor. In Hour 20, Special Classes and Functions, 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 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 12.1 creates a stripped-down, user-created object: SimpleCat. A real object would be larger and more expensive, but this is sufficient to show how often the copy constructor and destructor are called.
Listing 12.1 creates the SimpleCat object and then calls two functions. The first function receives the Cat by 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.
LISTING 12.1 PASSING OBJECTS BY REFERENCE

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:   //Listing 12.1
 2:   // Passing pointers to objects
 3:
 4:   #include <iostream.h>
 5:
 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\n;
17:   }
18:
19:   SimpleCat::SimpleCat(SimpleCat& rhs)
20:   {
21:          cout << Simple Cat Copy Constructor\n;
22:   }
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_178 next page >

If you like this book, buy it!