Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 279

9


Making a cat...
Simple Cat constructor...
Frisky is 1 years old
Frisky is 5 years old
Calling FunctionTwo...
FunctionTwo. Returning...
Frisky is now 5 years old
Frisky is 5 years old
Simple Cat Destructor...
The output is identical to that produced by Listing 9.11. The only significant
change is that FunctionTwo()now takes and returns a reference to a constant
object. Once again, working with references is somewhat simpler than working with
pointers, and the same savings and efficiency are achieved, as well as the safety provided
by using const.

OUTPUT


ANALYSIS

constReferences
C++ programmers do not usually differentiate between “constant reference to a
SimpleCatobject” and “reference to a constant SimpleCatobject.” References them-
selves can never be reassigned to refer to another object, and so they are always con-
stant. If the keyword constis applied to a reference, it is to make the object referred to
constant.

Knowing When to Use References Versus Pointers ............................................


Experienced C++ programmers strongly prefer references to pointers. References are
cleaner and easier to use, and they do a better job of hiding information, as you saw in
the previous example.
References cannot be reassigned, however. If you need to point first to one object and
then to another, you must use a pointer. References cannot be null, so if any chance
exists that the object in question might be null, you must not use a reference. You must
use a pointer.
An example of the latter concern is the operator new. If newcannot allocate memory on
the free store, it returns a null pointer. Because a reference shouldn’t be null, you must
not initialize a reference to this memory until you’ve checked that it is not null. The fol-
lowing example shows how to handle this:
int *pInt = new int;
if (pInt != NULL)
int &rInt = *pInt;
Free download pdf