Step 1 of 5
References are aliases
A reference is another name (an alias) for an existing variable. It isn't a copy and it isn't a separate box: using the reference is using the original.
#include <iostream>
int main() {
int score = 10;
int& s = score;
s += 5;
std::cout << score << "\n";
score = 100;
std::cout << s << "\n";
int other = 7;
s = other;
std::cout << score << "\n";
}
15
100
7
Declaring one
Put & after the type: int& s = score; makes s refer to score. From then on, s and score are two names for the same int.
How references differ from pointers
A reference does the same job as a pointer in many situations (reaching another variable), with fewer ways to go wrong:
| Property | Pointer | Reference |
|---|---|---|
| Must be initialized | no | yes |
| Can be null | yes | no |
| Can be changed to refer elsewhere | yes | no |
| Syntax to use the target | *p, p->x |
just the name |
Look at the last part of the example carefully: s = other; does not make s refer to other. A reference is bound once, forever. The assignment copies other's value (7) into the variable s refers to, which is score.
The & symbol is overloaded again: in a declaration after a type (int&) it means "reference"; in an expression before a variable (&x) it still means "address of".
Your turn: make alias a reference to money, then spend 800 through it.