References as Aliases

You can think of a C++ reference as an alias for a variable; that is, an alternate name for that variable. When you initialize a reference, you associate it with a variable. The reference is permanently associated with that variable; you cannot change the reference to be an alias for a different variable later on.

The unary & operator identifies a reference, as illustrated below:

int actualint;

int &otherint = actualint; // Reference declaration

These statements declare an integer named actualint and tell the compiler that actualint has another name, otherint. Now all operations on either name have the same result.

The following example shows how you can use a variable and a reference to that variable interchangeably:

// The reference

#include <iostream.h>

void main()

{

int actualint = 123;

int &otherint = actualint;

cout << '\n' << actualint;

cout << '\n' << otherint;

otherint++;

cout << '\n' << actualint;

cout << '\n' << otherint;

actualint++;

cout << '\n' << actualint;

cout << '\n' << otherint;

}

The example shows that operations on otherint act upon actualint. The program displays the following output, showing that otherint and actualint are simply two names for the same item:

123

123

124

124

125

125

A reference is not a copy of the variable to which it refers. Instead, it is the same variable under a different name.

The following example displays the addresses of a variable and a reference to that variable.

// Addresses of references

#include <iostream.h>

void main()

{

int actualint = 123;

int &otherint = actualint;

cout << &actualint << ' ' << &otherint;

}

When you run the program, it prints the same address for both identifiers, the value of which depends on the configuration of your system.

Note that the unary operator & is used in two different ways in the example above. In the declaration of otherint, the & is part of the variable's type. The variable otherint has the type int &, or “reference to an int.” This usage is unique to C++. In the cout statement, the & takes the address of the variable it is applied to. This usage is common to both C and C++.