Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

References are Not Variables

 

In C++, a reference  is an alternative name for a variable. The declaration of a reference looks very much like the declaration of a variable. However, a reference is not a variable. The notation tex2html_wrap_inline73429 denotes a reference to a variable of type T. For example the code sequence

int i = 57;
int& r = i;
defines one variable, i, and one reference, r.

In C++ all references must be initialized. In this case the reference r refers to the variable i. A reference can be used in a program everywhere that a variable can be used. In particular, if the reference r is used where a r-value is required, it is the r-value of i that is obtained. Similarly, if the reference r is used where an l-value is required, it is the l-value of i that is obtained.

Is it important to note that in C++, despite appearances, there are no operators that operate on references. In particular, it is not possible to change the variable to which a reference refers. And since every reference must be initialized by associating it with a variable, there is no such thing as a null reference. References are mainly used in C++ programs to specify the arguments and return values of functions.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.