< previous page page_163 next page >

Page 163
LISTING 11.1 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
11:         intOne = 5;
12:         cout << intOne:  << intOne << endl;
13:         cout << rSomeRef:  << rSomeRef << endl;
14:
15:         rSomeRef = 7;
16:         cout << intOne:  << intOne << endl;
17:         cout << rSomeRef:  << rSomeRef << endl;
18:         return 0;
19:    }

Output:
intOne: 5
rSomeRef: 5
intOne: 7
rSomeRef: 7
Analysis: On line 8, a local int variable, intOne, is declared. On line 9, a reference to an int, rSomeRef, is declared and initialized to refer to intOne. If you declare a reference but don't initialize it, you will get a compile-time error. References must be initialized.
On line 11, intOne is assigned the value 5. On lines 12 and 13, the values in intOne and rSomeRef are printed, and are (of course) the same, because rSomeRef is simply the reference to intOne.
On line 15, 7 is assigned to rSomeRef. Because this is a reference, it is an alias for intOne, thus the 7 is really assigned to intOne, as is shown by the printouts on lines 16 and 17.
Using the Address of Operator on References
If you ask a reference for its address, it returns the address of its target. That is the nature of referencesthey are aliases for the target. Listing 11.2 demonstrates this.
LISTING 11.2 TAKING THE ADDRESS OF A REFERENCE

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    //Listing 11.2
 2:    // Demonstrating the use of References
 3:
 4:    #include <iostream.h>
 5:
 6:    int main()
 7:    {
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_163 next page >

If you like this book, buy it!