Wrox Press C++ Tutorial


Using References

A reference appears to be similar to a pointer in many respects, which is why we've introduced it here, but it isn't the same thing at all. Its real significance will only become apparent when we get to discuss its use with functions, particularly in the context of object-oriented programming. Don't be misled by its simplicity and what might seem to be a trivial concept. As you will see later, references provide some extraordinarily powerful facilities, and in some contexts it will enable you to achieve results that would be impossible without using them.

What is a Reference?

A reference is an alias for another variable. It has a name that can be used in place of the original variable name. Since it is an alias, and not a pointer, the variable for which it is an alias has to be specified when the reference is declared, and unlike a pointer, a reference can't be altered to represent another variable.

Declaring and Initializing References

If we have a variable declared as follows,

long number = 0;

we can declare a reference for this variable using the following declaration statement:

long& rnumber = number; // Declare a reference to variable number

The ampersand following the type long and preceding the name rnumber, indicates that a reference is being declared, and the variable name it represents, number, is specified as the initializing value following the equals sign. Therefore, rnumber is of type 'reference to long'. The reference can now be used in place of the original variable name. For example, this statement,

rnumber += 10;

has the effect of incrementing the variable number by 10.

Let's contrast the reference rnumber with the pointer pnumber, declared in this statement:

long* pnumber = &number; // Initialize a pointer with an address

This declares the pointer pnumber, and initializes it with the address of the variable number. This then allows the variable number to be incremented with a statement such as:

*pnumber += 10;         // Increment number through a pointer

You should see a significant distinction between using a pointer and using a reference. The pointer needs to be de-referenced and whatever address it contains is used to access the variable to participate in the expression. With a reference there is no need for de-referencing. In some ways, a reference is like a pointer that has already been de-referenced, although it can't be changed to reference another variable. The reference is the complete equivalent of the variable for which it is a reference. A reference may seem like just an alternative notation for a given variable, and here it certainly appears to behave like that. However, we shall see when we come to discuss functions in C++ that this is not quite true, and that it can provide some very impressive extra capabilities.


© 1998 Wrox Press