Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 277

9


SimpleCathas added two accessor functions,GetAge()on line 13, which is a
constfunction, and SetAge()on line 14, which is not a constfunction. It has
also added the member variable itsAgeon line 17.
The constructor, copy constructor, and destructor are still defined to print their messages.
The copy constructor is never called, however, because the object is passed by reference
and so no copies are made. On line 42, an object is created, and its default age is printed,
starting on line 43.
On line 47,itsAgeis set using the accessor SetAge, and the result is printed on line 48.
FunctionOneis not used in this program, but FunctionTwo()is called. FunctionTwo()
has changed slightly; the parameter and return value are now declared, on line 36, to take
a constant pointer to a constant object and to return a constant pointer to a constant object.
Because the parameter and return value are still passed by reference, no copies are made
and the copy constructor is not called. The object being pointed to in FunctionTwo(),
however, is now constant, and thus cannot call the non-constmethod,SetAge(). If the
call to SetAge()on line 66 was not commented out, the program would not compile.
Note that the object created in main()is not constant, and Friskycan call SetAge().
The address of this nonconstant object is passed to FunctionTwo(), but because
FunctionTwo()’s declaration declares the pointer to be a constant pointer to a constant
object, the object is treated as if it were constant!

References as an Alternative ..........................................................................


Listing 9.11 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, and thereby
solves 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 within the
function if a reference were passed in, rather than a pointer. Listing 9.12 illustrates this.

LISTING9.12 Passing References to Objects


1: //Listing 9.12 - Passing references to objects
2:
3: #include <iostream>
4:
5: using namespace std;
6: class SimpleCat
7: {
8: public:
9: SimpleCat();
10: SimpleCat(SimpleCat&);

ANALYSIS
Free download pdf