Sams Teach Yourself C++ in 21 Days

(singke) #1
You create a reference by writing the type of the target object, followed by the reference
operator (&), followed by the name of the reference, followed by an equal sign, followed
by the name of the target object.
References can have any legal variable name, but some programmers prefer to prefix ref-
erence names with the letter “r.” Thus, if you have an integer variable named someInt,
you can make a reference to that variable by writing the following:
int &rSomeRef = someInt;
This statement is read as “rSomeRefis a reference to an integer. The reference is initial-
ized to refer to someInt.” References differ from other variables that you can declare in
that they must be initialized when they are declared. If you try to create a reference vari-
able without assigning, you receive a compiler error. Listing 9.1 shows how references
are created and used.

256 Day 9


Note that the reference operator (&) is the same symbol as the one used for
the address-of operator. These are not the same operators, however,
although clearly they are related.
The space before the reference operator is required; the space between the
reference operator and the name of the reference variable is optional. Thus
int &rSomeRef = someInt; // ok
int & rSomeRef = someInt; // ok

NOTE

LISTING9.1 Creating and Using References
1: //Listing 9.1 - 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: rSomeRef = 7;
16: cout << “intOne: “ << intOne << endl;
17: cout << “rSomeRef: “ << rSomeRef << endl;
18:
19: return 0;
20: }
Free download pdf