References
A Rocket Run function should heal the player by 20 points. You write it, call it, and the player's health does not budge. The function worked on a copy. References are C++'s clean way of saying "not a copy, the real thing".
The rule
A reference is another name for an existing object, bound once, forever.
int health = 50;
int& hp = health; // hp is another name for health
hp += 20; // health is now 70Rules that make references simpler than pointers:
- A reference must be bound when it is declared.
int& hp;on its own is an error. - It can never be re-bound to a different object. Assigning to it assigns to the object it names.
- There is no null reference to check for, and no
*or->to write.
Their main job is function parameters:
void healCopy(int hp) { hp += 20; } // copy: caller unchanged
void heal(int& hp) { hp += 20; } // reference: caller changed
void showName(const std::string& name) { // read-only, no copy
std::cout << name << '\n';
}const T& is the everyday choice for passing large objects you only read: no copy is made, and const promises you will not change the caller's data.
The shortcut
Choose a parameter type with three questions:
- Must the function change the caller's object? Use
T&. - Only reading something large (a string, a vector, a big struct)? Use
const T&. - Only reading something small (an
int, adouble, abool)? Pass by value,T.
Setup
int a = 1, b = 2; int& r = a;binds r to a, forever.
The trap is thinking r = b points r at b. A reference cannot be moved; assignment always goes through to the original object.
Drills
Answer fast — trust the rule.
void heal(int hp) { hp += 20; } is called on health equal to 50. What is health afterwards?
With void heal(int& hp) { hp += 20; } instead, what is health afterwards?
After int a = 1, b = 2; int& r = a; r = b; r = 9;, what are a and b?
Which parameter type fits a function that only reads a long player name?
What happens with the declaration int& r; on its own?
Remember
- A reference is another name for an existing object, bound once, forever.
- Shortcut: change it,
T&; read something big,const T&; read something small,T. - Trap: assigning to a reference changes the object; it never re-binds.
