Loading lessons...
Create References
Create References
A reference is another name for an existing variable - an alias. Two names, one object, no copy.
Declaring a reference
#include <string>
using namespace std;
string food = "Pizza";
string &meal = food; // meal is a reference to food
foodis a normal string.mealis a reference tofood- a second name for the same data.
The & that appears in the declaration (right after the type) is what makes meal a reference.
Two names, one value
cout << meal << endl; // Pizza
cout << food << endl; // Pizza
Both names print the same value, because both refer to the same location. Change one name and the change is visible through the other:
meal = "Burger";
cout << food << endl; // Burger
Same memory address
A reference makes no copy - meal and food are literally the same object. They even share the same memory address:
cout << &food << endl; // 0x7ffe0000a1c
cout << &meal << endl; // 0x7ffe0000a1c (same!)
Where the & goes
The & in string &meal is part of the declaration - it signals "this name is a reference". A reference must be bound to a variable when it is declared; there is no "empty reference".
TL;DR
- A reference is an alias: another name for an existing variable.
- Declare it with
&after the type:string &meal = food;. - No copy - both names share the same memory address.
- Changing one name changes the other, because they are one object.