Modern C++ Foundations · 8 min read · Intermediate
References, const & Functions
Pass large objects without copying using const references (const T&) and mutate arguments cleanly with T&.
What you'll learn
- Understand how C++ references differ from raw pointers
- Pass read-only strings and containers by const T& to avoid copies
- Use function overloading and default parameter values cleanly
A reference (int& ref = x;) is an alias for an existing variable. Unlike a pointer, a reference cannot be nullptr and cannot be reseated to point somewhere else, making it much safer for everyday function parameters.
Parameter Passing Cheat Sheet
- Small primitives (
int,double,bool): pass by value (int n). - Read-only objects (
std::string,std::vector): pass by const reference (const std::string& name). - In-place mutation: pass by non-const reference (
int& counter).
Fill-in-the-Blank Exercise
Pass by Const Reference
Accept a read-only std::string without copying it.
void greet( std::string name) {
std::cout << "Hello, " << name << "\n";
}Interactive Code Lab
C++references.cpp
Expected OutputClick “Run Live” to compile with GCC 13 (C++20)
Alex: 100
Check Your Understanding
Score: 0 / 1
1. How should you pass a large std::vector to a function that only reads its elements?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.