Lesson 4 | Reference declarations |
Objective | Create aliases for variables using reference declarations. |
C++ Reference Declarations
C++ allows
reference declarations[1] so you can create aliases for variables. These declarations are typically of the form:
type& identifier = variable
Example
Here are two examples of reference declarations:
int n;
int& nn = n;
double a[10];
double& last = a[9];
The name nn
is an alias for n
. They refer to the same place in memory, and modifying the value of nn
is equivalent to modifying n
and vice versa.
The name last
is an alternative way of referring to the single array element a[9]
.
An alias, once declared, cannot be changed. In other words, if you declared last
as an alias for the array element a[9]
, you could not also declare last
as an alias for the array element a[1]
.
Reference declarations that are definitions must be initialized, usually as simple variables.
The initializer is the lvalue expression, which gives the variable's location in memory.
When a variable i
is declared, it has an address and memory location associated with it. When a reference variable r
is declared and initialized to i
, it is identical to i
. It does not have a separate identity from the i
.
[1]: Reference declarations declare the identifier to be an alternative name or
alias for a variable specified in an initialization of the reference.