Sams Teach Yourself C++ in 21 Days

(singke) #1
Once again, on lines 8 and 9, an integer variable and a reference to an integer are
declared. The integer is assigned the value 5 on line 11, and the values and their
addresses are printed on lines 12–15.
On line 17, a new variable,intTwo, is created and initialized with the value 8. On line
18, the programmer tries to reassign rSomeRefto now be an alias to the variable intTwo,
but that is not what happens. What actually happens is that rSomeRefcontinues to act as
an alias for intOne, so this assignment is equivalent to the following:
intOne = intTwo;
Sure enough, when the values of intOneand rSomeRefare printed (lines 19–21), they are
the same as intTwo. In fact, when the addresses are printed on lines 22–24, you see that
rSomeRefcontinues to refer to intOneand not intTwo.

260 Day 9


ANALYSIS

DOuse references to create an alias to
an object.
DOinitialize all references.

DON’Ttry to reassign a reference.
DON’Tconfuse the address-of operator
with the reference operator.

DO DON’T


Referencing Objects ............................................................................................


Any object can be referenced, including user-defined objects. Note that you create a ref-
erence to an object, but not to a class. For instance, your compiler will not allow this:
int & rIntRef = int; // wrong
You must initialize rIntRefto a particular integer, such as this:
int howBig = 200;
int & rIntRef = howBig;
In the same way, you don’t initialize a reference to a Cat:
Cat & rCatRef = Cat; // wrong
You must initialize a reference to a particular Catobject:
Cat Frisky;
Cat & rCatRef = Frisky;
References to objects are used just like the object itself. Member data and methods are
accessed using the normal class member access operator (.), and just as with the built-in
types, the reference acts as an alias to the object. Listing 9.4 illustrates this.
Free download pdf