References and pointers
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Variables live at addresses
Every variable sits somewhere in memory, and that place has an address. Pointers and references are two ways to talk about an existing variable instead of making a copy. This is the topic where C++ stops feeling like other languages, so take it slowly.
References
A reference is another name for an object that already exists. You create it with & after the type.
#include <iostream>
int main() {
int score{10};
int& alias = score; // alias is another name for score
alias = 25;
std::cout << score << "\n"; // 25
return 0;
}
Two rules make references simple. A reference must be bound to something when it is created, and it can never be re-bound to a different object afterwards. There is no such thing as a null reference in correct code.
Why references matter for functions
Remember that arguments are copied by default. A reference parameter avoids the copy, and a non-const one lets the function change the caller's variable.
#include <iostream>
#include <string>
#include <vector>
void addBonus(int& points) { // can modify caller's value
points += 5;
}
std::size_t totalLength(const std::vector<std::string>& words) { // read only, no copy
std::size_t sum = 0;
for (const auto& w : words) sum += w.size();
return sum;
}
int main() {
int points{40};
addBonus(points);
std::cout << points << "\n"; // 45
std::vector<std::string> words{"alpha", "beta"};
std::cout << totalLength(words) << "\n"; // 9
}
This gives a rule of thumb I use every day. Small types like int, double and char: pass by value. Larger types you only read: pass by const T&. Things the function must change: pass by T&. A const reference can also bind to a temporary, so totalLength({"a", "b"}) works.
Pointers
A pointer is a variable that holds an address. Unlike a reference, it can be null, and it can be changed to point somewhere else. You get an address with & (in an expression) and follow it with *.
#include <iostream>
int main() {
int age{30};
int* p = &age; // p holds the address of age
std::cout << *p << "\n"; // 30 (dereference)
*p = 31; // changes age through the pointer
std::cout << age << "\n"; // 31
int* nothing = nullptr; // points to nothing
if (nothing == nullptr) {
std::cout << "nothing points nowhere\n";
}
return 0;
}
The symbols are confusing because & and * mean different things in declarations and expressions. In a declaration, int* means "pointer to int" and int& means "reference to int". In an expression, &x means "address of x" and *p means "the thing p points to".
Use nullptr for the null pointer. Older code uses NULL or 0, which can pick the wrong overload. Dereferencing a null pointer is undefined behaviour; on most systems you get a crash, which is the lucky outcome.
Pointers and const
Read declarations from right to left. const int* p is a pointer to a constant int: you can move the pointer, but not change the value through it. int* const p is a constant pointer to an int: the value can change, but the pointer cannot move. Most of the time you want the first form.
Pointer arithmetic and arrays
Adding one to a pointer moves it by one element, not one byte. This is how arrays work under the hood, and it is why raw pointers are easy to misuse.
int nums[3]{10, 20, 30};
int* q = nums; // array name converts to pointer to first element
std::cout << *(q + 2) << "\n"; // 30, same as nums[2]
In modern code you rarely do this by hand. std::vector and std::span do the same job with bounds you can check.
Dangling pointers and references
A dangling pointer points at something that no longer exists. The compiler often cannot warn you.
int* bad() {
int local{5};
return &local; // local dies when the function returns
} // the caller receives a dangling pointer
The same happens when you return a reference to a local variable. The variable is destroyed on return, so the reference refers to dead memory. Reading it might even work for a while, which is the worst case, because the bug hides until it does not.
Which one should I use?
| Need | Use |
|---|---|
| Function reads a big object | const T& |
| Function modifies the caller's object | T& |
| Parameter may be "nothing" | A pointer, or std::optional |
| Need to re-point at different objects | A pointer |
| Owning heap memory | A smart pointer, not a raw pointer (see the smart pointers lesson) |
A raw pointer in modern C++ should mean "I am borrowing this, I do not own it". Ownership gets its own tools.
The common mistake
Returning a reference or pointer to a local variable is the big one. A second very common one is writing int* a, b; and expecting two pointers. Only a is a pointer; b is a plain int. Declare one variable per line and the confusion disappears. And third, using a pointer after the object it pointed to has been destroyed, for instance after a std::vector grows and moves its elements.
Try it yourself
- Write
void swapInts(int& a, int& b)and test it. Then write the same with pointers and compare the call syntax. - Write a function that takes
const std::string&and returns how many vowels it contains. - Write the dangling-pointer function above, compile with
-Wall -Wextra, and see whether your compiler warns about it.
#include <iostream>
int main() {
int score{10};
int& alias = score; // alias is another name for score
alias = 25;
std::cout << score << "\n"; // 25
return 0;
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account