< previous page page_183 next page >

Page 183
Because the parameter and return value are still passed by reference, no copies are made and the copy constructor is not called. The pointer in FunctionTwo(), however, is now constant and, thus, cannot call the non-const method, SetAge(). If the call to SetAge() on line 62 were not commented out, the program would not compile.
Note that the object created in main() is not constant, and Frisky can call SetAge(). The address of this non-constant object is passed to FunctionTwo(), but because FunctionTwo()'s declaration declares the pointer to be a constant pointer, the object is treated as if it were constant!
References as an Alternative
Listing 12.3 solves the problem of making extra copies and, thus, saves the calls to the copy constructor and destructor. It uses constant pointers to constant objects, thereby solving the problem of the function changing the object. It is still somewhat cumbersome, however, because the objects passed to the function are pointers.
Because you know the object will never be null, it would be easier to work with in the function if a reference were passed in rather than a pointer. Listing 12.3 illustrates this.
LISTING 12.3 PASSING REFERENCES TO OBJECTS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:   //Listing 12.3
 2:   // Passing references to objects
 3:
 4:   #include <iostream.h>
 5:
 6:   class SimpleCat
 7:   {
 8:   public:
 9:           SimpleCat();
10:          SimpleCat(SimpleCat&);
11:          ~SimpleCat();
12:
13:          int GetAge() const { return itsAge; }
14:          void SetAge(int age) { itsAge = age; }
15:
16:  private:
17:          int itsAge;
18:  };
19:
20:  SimpleCat::SimpleCat()
21:  {
22:         cout << Simple Cat Constructor\n;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_183 next page >

If you like this book, buy it!