Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 257

9


intOne: 5
rSomeRef: 5
intOne: 7
rSomeRef: 7
On line 8, a local integer variable,intOne, is declared. On line 9, a reference to
an integer (int),rSomeRef, is declared and initialized to refer to intOne. As
already stated, if you declare a reference but don’t initialize it, you receive a compile-
time error. References must be initialized.
On line 11,intOneis assigned the value 5. On lines 12 and 13, the values in intOneand
rSomeRefare printed, and are, of course, the same.
On line 15, 7 is assigned to rSomeRef. Because this is a reference, it is an alias for intOne,
and 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..............................................


You have now seen that the &symbol is used for both the address of a variable and to
declare a reference. But what if you take the address of a reference variable? If you ask a
reference for its address, it returns the address of its target. That is the nature of refer-
ences. They are aliases for the target. Listing 9.2 demonstrates taking the address of a
reference variable called rSomeRef.

LISTING9.2 Taking the Address of a Reference


1: //Listing 9.2 - Demonstrating the use of references
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:
15: cout << “&intOne: “ << &intOne << endl;
16: cout << “&rSomeRef: “ << &rSomeRef << endl;
17:
18: return 0;
19: }

OUTPUT


ANALYSIS
Free download pdf