Pass by Reference
Overview
By default, C++ operates on a policy called 'Pass by Value'. When you pass a variable into a function, C++ creates a complete physical clone (a copy) of that variable in a new memory address. The function only modifies the clone, leaving the original variable completely untouched.
While safe, this is a catastrophic performance bottleneck if you are passing a massive std::vector containing 10,000 items. Copying it takes heavy CPU time. Pass by Reference (using the & symbol) solves this. Instead of copying the data, it passes the exact Memory Address of the original variable. The function directly modifies the original data, taking 0 extra memory and operating instantly.
Syntax
// --- 1. PASS BY VALUE (Makes a copy) ---
void failToLevelUp(int level) {
level++; // Only modifies the local copy!
}
// --- 2. PASS BY REFERENCE (Modifies the original) ---
void levelUp(int& level) {
level++; // Directly mutates the original variable!
}
int main() {
int myLevel = 1;
failToLevelUp(myLevel);
// myLevel is still 1
levelUp(myLevel);
// myLevel is now 2!
return 0;
}Common Pitfalls
- Unintentional Mutation. If you pass a variable by reference solely to avoid the performance cost of copying it, you run the risk of accidentally modifying the original data. To fix this, use
const int&(a constant reference) to get the speed of a reference while locking the data from being changed.
Interview Questions
void process(const std::string& text)) considered the gold standard in professional C++?It provides the best of both worlds. The & symbol ensures we do not waste CPU cycles creating a copy of the massive string object. The const keyword mathematically guarantees that the function cannot accidentally modify or corrupt the original string. It is perfectly optimized and perfectly safe.
Real-World Example
Using Pass by Reference to allow a single function to practically 'return' multiple values at once.
#include <iostream>
// We want to calculate both Area and Perimeter simultaneously.
// We pass the results by reference to modify the original variables!
void calculateRect(int w, int h, int& areaOut, int& perimOut) {
areaOut = w * h;
perimOut = 2 * (w + h);
}
int main() {
int area = 0, perimeter = 0;
calculateRect(10, 5, area, perimeter);
std::cout << "Area: " << area << " | Perimeter: " << perimeter << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Pass by Reference with these quick questions.