A reference in C++ is an alias for another variable — meaning it is not a copy.
It is just another name for an already-existing variable.
Learn software development training in abuja
Think of it like giving someone a nickname.
The person doesn’t change — you just have two names pointing to the same person.
int x = 10;
int& ref = x; // OK
int& badRef; // ❌ ERROR — must be initialized Learn C++ online from a comprehensive edtech platform.
There is no null reference in standard C++. It must bind to a real object.
Once a reference is bound, it forever refers to the same object.
int a = 5;
int b = 20;
int& r = a;
r = b; // assigns value of b → a
// does NOT make r refer to b
(Useful for performance)
Pass a reference to allow the function to change the original variable.
No dereferencing operators required.
| Feature | Reference | Pointer |
|---|---|---|
| Must be initialized? | ✔ Yes | ❌ No |
| Can be NULL? | ❌ No | ✔ Yes |
| Can change what it refers to? | ❌ No | ✔ Yes |
| Syntax | Simple | Requires * and -> |
| Memory address? | Same as original | Has its own address |
void addOne(int& num) {
num += 1; // modifies original
}
int main() {
int a = 10;
addOne(a);
// a is now 11
} Used to return a reference to a variable, usually class members or containers.
int& getElement(std::vector<int>& v, int index) {
return v[index];
}
int main() {
std::vector<int> nums = {1,2,3};
getElement(nums, 1) = 10; // modifies nums[1]
} Used to avoid copying while guaranteeing no modification.
void print(const std::string& name) {
std::cout << name;
} ✔ Faster (no copy)
✔ Safe (can’t modify)
int&)Refers to an existing variable.
const int&)Can bind to literals and temporaries:
const int& r = 10; // allowed int&&) — C++11Used for move semantics and performance optimizations.
int&& temp = 5; Pointers are like phone numbers — you can dial different people (change address).
References are like nicknames — they stick to the same person forever.
const& avoids copying while preventing modification.&& rvalue references enable move semantics.Latest tech news and coding tips.
What is Steam Locomotive (sl)? Steam Locomotive (sl) is a small terminal program on Unix/Linux systems…
What is Rate Limiting? Download this article as a PDF on the Codeflare Mobile App…
Learn on the Go. Download the Codeflare Mobile from iOS App Store. 1. What is…
Download the Codeflare iOS app and learn on the Go 1. What UI and UX…
1. Running Everything as Root One of the biggest beginner errors. Many new users log…
A keylogger is a type of surveillance software or hardware that records every keystroke made…