Exploiting References 259
9
Attempting to Reassign References (Not!) ....................................................
Reference variables cannot be reassigned. Even experienced C++ programmers can be
confused by what happens when you try to reassign a reference. Reference variables are
always aliases for their target. What appears to be a reassignment turns out to be the
assignment of a new value to the target. Listing 9.3 illustrates this fact.
LISTING9.3 Assigning to a Reference
1: //Listing 9.3 - //Reassigning a reference
2:
3: #include <iostream>
4:
5: int main()
6: {
7: using namespace std;
8: int intOne;
9: int &rSomeRef = intOne;
10:
11: intOne = 5;
12: cout << “intOne: “ << intOne << endl;
13: cout << “rSomeRef: “ << rSomeRef << endl;
14: cout << “&intOne: “ << &intOne << endl;
15: cout << “&rSomeRef: “ << &rSomeRef << endl;
16:
17: int intTwo = 8;
18: rSomeRef = intTwo; // not what you think!
19: cout << “\nintOne: “ << intOne << endl;
20: cout << “intTwo: “ << intTwo << endl;
21: cout << “rSomeRef: “ << rSomeRef << endl;
22: cout << “&intOne: “ << &intOne << endl;
23: cout << “&intTwo: “ << &intTwo << endl;
24: cout << “&rSomeRef: “ << &rSomeRef << endl;
25: return 0;
26: }
intOne: 5
rSomeRef: 5
&intOne: 0012FEDC
&rSomeRef: 0012FEDC
intOne: 8
intTwo: 8
rSomeRef: 8
&intOne: 0012FEDC
&intTwo: 0012FEE0
&rSomeRef: 0012FEDC
OUTPUT