< previous page page_166 next page >

Page 166
Analysis: Once again, an integer variable and a reference to an integer are declared, on lines 8 and 9. The integer is assigned the value 5 on line 11, and the values and their addresses are printed on lines 1215.
On line 17 a new variable, intTwo, is created and initialized with the value 8. On line 18 the programmer tries to reassign rSomeRef to now be an alias to the variable intTwo, but that is not what happens. What actually happens is that rSomeRef continues to act as an alias for intOne, so this assignment is exactly equivalent to the following:
intOne = intTwo;
Sure enough, when the values of intOne and rSomeRef are printed (lines 1921) they are the same as intTwo. In fact, when the addresses are printed on lines 2224, you see that rSomeRef continues to refer to intOne and not intTwo.
DODON'T
DO use references to create an alias to an object.DON'T try to reassign a reference.
DO initialize all references.DON'T confuse the address of operator with the reference operator.

What Can Be Referenced?
Any object can be referenced, including user-defined objects. Note that you create a reference to an object, not to a class. You do not write this:
int & rIntRef = int;    // wrong
You must initialize rIntRef to 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 rCatRef to a particular CAT object:
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.

 
< previous page page_166 next page >

If you like this book, buy it!