1.16. Reference Variables

[ fromfile: references.xml id: references ]

You observed earlier that an object (in the most general sense) is a contiguous region of storage. An lvalue is an expression that refers to an object. Examples of lvalues are variables, array cells, and dereferenced pointers. In essence, an lvalue is anything with a memory address that can be given a name. By contrast, temporary or constant expressions such as i+1 or 3 are not lvalues.

In C++, a reference provides a mechanism for assigning an alternative name to an lvalue. References are especially useful for avoiding making copies when copying is costly or unnecessary, for example, when passing a large object as a parameter to a function. A reference must be initialized when it is declared, and the initializer must be an lvalue.

To create a reference to an object of type SomeType, a variable must be declared to be of type SomeType&. For example:

  int n;
  int& rn = n;

The ampersand & following the int indicates that rn is an int reference. The reference variable rn is an alias for the actual variable n. Note that the & is being used here as a type modifier in a declaration, rather than as an operator on an lvalue.

For its entire life, a reference variable will be an alias for the actual lvalue that initialized it. This association cannot be revoked or transferred. For example:

 int a = 10, b = 20;
 int& ra = a;         // ra is an alias for a
 ra = b;              // this causes a to be assigned the value 20

 const int c = 45;    // c is a constant: its value is read-only.
 const int& rc = c;   // legal but probably not very useful.
 rc = 10;             // compiler error - const data may not be changed.

You have surely noticed that the use of the ampersand in this section might be confused with its use in the earlier section on pointers. To avoid confusion just remember these two facts.

  1. The address-of operator applies to an object and returns its address. Hence, it appears only on the right side of an assignment or in an initializing expression for a pointer variable.

  2. In connection with references, the ampersand is used only in the declaration of a reference. Hence, it appears only between the type name and the reference name as it is declared.

[Note] Note

For reference declarations, we recommend placing the ampersand immediately to the right of the type name:

 Type& ref(initLval);