< previous page page_162 next page >

Page 162
What Is a Reference?
New Term: A reference is an alias. When you create a reference, you initialize it with the name of another object, the target. From that moment on, the reference acts as an alternative name for the target, and anything you do to the reference is really done to the target.
That's it. Some C++ programmers will tell you that references are pointers; that is not correct. Although references are often implemented using pointers, that is a matter of concern only to creators of compilers; as a programmer you must keep these two ideas distinct.
Pointers are variables that hold the address of another object. References are aliases to another reference.
Creating a Reference.
You create a reference by writing the type of the target object, followed by the reference operator (&), followed by the name of the reference. References can use any legal variable name, but for this book we'll prefix all reference names with r. So, if you have an integer variable named someInt, you can make a reference to that variable by writing the following:
int &rSomeRef = someInt;
This is read as rSomeRef is a reference to an integer that is initialized to refer to someInt. Listing 11.1 shows how references are created and used.
Note that the reference operator (&) is the same symbol as the one used for the address of the operator.

LISTING 11.1 CREATING AND USING REFERENCES

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    //Listing 11.1
 2:    // Demonstrating the use of References
 3:
 4:    #include <iostream.h>
 5:
 6:    int main()
 7:    {
 8:         int  intOne;
 9:         int &rSomeRef = intOne;
10:
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_162 next page >

If you like this book, buy it!