< previous page page_165 next page >

Page 165
Even experienced C++ programmers, who know the rule that references cannot be reassigned and are always aliases for their target, can be confused by what happens when you try to reassign a reference. What appears to be a reassignment turns out to be the assignment of a new value to the target. Listing 11.3 illustrates this fact.
LISTING 11.3 ASSIGNING TO A REFERENCE

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:       //Listing 11.3
 2:       //Reassigning a reference
 3:
 4:       #include <iostream.h>
 5:
 6:       int main()
 7:       {
 8:            int  intOne;
 9:            int &rSomeRef = intOne;
10:
11:            intOne = 5;
12:            cout << intOne:\t << intOne << endl;
13:            cout << rSomeRef:\t << rSomeRef << endl;
14:            cout << &intOne:\t  << &intOne << endl;
15:            cout << &rSomeRef:\t << &rSomeRef << endl;
16:
17:            int intTwo = 8;
18:            rSomeRef = intTwo; // not what you think!
19:            cout << \nintOne:\t << intOne << endl;
20:            cout << intTwo:\t << intTwo << endl;
21:            cout << rSomeRef:\t << rSomeRef << endl;
22:            cout << &intOne:\t  << &intOne << endl;
23:            cout << &intTwo:\t  << &intTwo << endl;
24:            cout << &rSomeRef:\t << &rSomeRef << endl;
25:            return 0;
26:     }

Output:
intOne:     5
rSomeRef:   5
&intOne:    0x0012FF7C
&rSomeRef:  0x0012FF7C

intOne:     8
intTwo:     8
rSomeRef:   8
&intOne:    0x0012FF7C
&intTwo:    0x0012FF74
&rSomeRef:  0x0012FF7C

 
< previous page page_165 next page >

If you like this book, buy it!