Lesson 4 | Reference declarations |
Objective | Create aliases for variables using reference declarations. |
C++ Reference Declarations
C++20 does offer several mechanisms that can effectively serve this purpose:
- References (since C++98):
- Type Aliases (since C++11):
- Structured Bindings (since C++17):
- `std::reference_wrapper` (since C++11):
- 5. Pointers:
Choose the appropriate mechanism based on your specific needs, considering factors like:
- Whether you need to modify the original variable through the alias.
- Whether you need to store the alias in a container or pass it to a function.
- Whether you want to create an alias for a specific variable or for a type in general.
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.