Article by Ayman Alheraki on April 1 2026 02:15 PM
A reference is an alias for an existing object. Once a reference is initialized to refer to an object, it cannot be made to refer to another object later.
x
int main() { int value{10}; int& ref = value;
std::cout << value << '\n'; std::cout << ref << '\n';}Here:
value is an int,
ref is a reference to value,
both names refer to the same object.
Because a reference refers to the original object, modifying the reference modifies the object itself.
xxxxxxxxxx
int main() { int value{10}; int& ref = value;
ref = 25;
std::cout << value << '\n'; // prints 25}A reference is not like an ordinary variable that can exist without referring to something. It must be initialized when declared.
xxxxxxxxxx// int& ref; // invalidThis is invalid because the compiler requires the reference to be bound to an object immediately.
Once initialized, a reference remains bound to the same object.
xxxxxxxxxx
int main() { int a{10}; int b{20};
int& ref = a; ref = b;
std::cout << a << '\n'; // prints 20 std::cout << b << '\n'; // prints 20}This does not make ref refer to b. Instead, it assigns the value of b to the object already referred to by ref, which is a.
References are extremely important in function interfaces.
xxxxxxxxxx
void increment(int& x) { ++x;}
int main() { int value{5}; increment(value);
std::cout << value << '\n'; // prints 6}This allows a function to modify the caller's object directly.
const referencesA const reference allows access to an object without copying it and without allowing modification.
xxxxxxxxxx
void print_name(const std::string& name) { std::cout << name << '\n';}This is one of the most common and important patterns in Modern C++.
A reference must refer to a valid object. If the referred object dies and the reference is still used, the program has a dangling reference.
xxxxxxxxxxint& bad_reference() { int local{42}; return local; // dangerous}The local variable is destroyed when the function ends, so the returned reference becomes invalid.