References and Dynamic Memory
Give a variable a nickname, hold its address, and borrow memory the smart way
new and must give back with delete.
- tell a reference apart from a pointer,
- explain where stack and heap memory live,
- allocate and free heap memory with
newanddeletewithout leaking.
1. A reference is a second name
A reference is just another name (an alias) for a variable that already exists. You create one with the & symbol in the declaration. After that, the reference and the original are the same box in memory: change one, and the other changes too.
Analogy: if your name is Alexander but your family calls you "Alex", both names point to the same person. Feed Alex lunch and Alexander is no longer hungry - because they are one and the same.
#include <iostream>
using namespace std;
int main() {
int score = 10;
int& alias = score; // alias is a SECOND name for score
alias = 25; // changing alias changes score
cout << score << endl; // 25
return 0;
}
Expected output: 25. Because alias is another name for score, writing to one writes to both. A reference must be given something to refer to when it is created, and it can never be moved to refer to a different variable later.
2. A pointer holds an address
A pointer is a variable whose value is the memory address of another variable. You declare it with * and read an address with the address-of operator &. To reach the value stored at that address you dereference the pointer, again with *.
Analogy: a pointer is like a sticky note with a friend's house address on it. The note is not the house - but by following the address you can visit the house and even rearrange the furniture inside.
#include <iostream>
using namespace std;
int main() {
int n = 42;
int* p = &n; // p holds the ADDRESS of n
cout << n << endl; // 42
cout << *p << endl; // 42 (value at that address)
*p = 100; // change n THROUGH the pointer
cout << n << endl; // 100
return 0;
}
Expected output: 42, then 42, then 100. Here &n means "the address of n", and *p means "the value at the address in p". Unlike a reference, a pointer can be empty (nullptr) and can be pointed at a different variable later.