A reference is an alias for another variable. Once you bind a reference to a variable, the reference acts as if it is that variable. Unlike pointers, references cannot be null and cannot be reassigned to point to something else.
Reference Basics
You declare a reference with an ampersand & after the
type. It must be initialized when declared. From that point on, any
operation on the reference affects the original variable:
#include <iostream>
int main() {
int original = 42;
int& ref = original;
std::cout << "Original: " << original << "\n";
std::cout << "Reference: " << ref << "\n";
ref = 100;
std::cout << "After change via ref:\n";
std::cout << "Original: " << original << "\n";
std::cout << "Reference: " << ref << "\n";
return 0;
}
ref is not a copy of original — it is
original under a different name. Changing one changes the
other because they are the same memory location.
References vs Pointers
References and pointers are related but different. A reference is like a pointer that you cannot reseat and cannot be null. Here is a quick comparison:
#include <iostream>
void withPointer(int* p) {
if (p) {
*p = *p + 10;
}
}
void withReference(int& r) {
r = r + 10;
}
int main() {
int a = 5;
int b = 5;
withPointer(&a);
withReference(b);
std::cout << "After pointer: " << a << "\n";
std::cout << "After reference: " << b << "\n";
int& cannotBeNull = a;
std::cout << "Reference value: " << cannotBeNull << "\n";
return 0;
}
With a pointer, you call the function with &a and you
check for null inside. With a reference, the syntax is cleaner — you
pass the variable directly and you know it cannot be null.
References as Function Parameters
The most common use of references is to avoid copying large objects when passing them to functions. This is called passing by reference:
#include <iostream>
#include <string>
void greet(const std::string& name) {
std::cout << "Hello, " << name << "!\n";
}
int main() {
std::string user = "Aisha";
greet(user);
return 0;
}
Using const with a reference promises the function will
not modify the argument. This gives you the efficiency of passing by
reference with the safety of passing by value.