What is a C++ reference? How is it different from a pointer, and when would you use each?
Show the explanation
A reference is another name for an existing object. Once it is bound, every use of the reference is a use of that object.
Reference int &r = x; | Pointer int *p = &x; | |
|---|---|---|
| Must be initialised | yes | no (but an uninitialised pointer is dangerous) |
| Can be null | no (no valid null reference exists) | yes: nullptr |
| Can be re-seated to another object | no; r = y copies y's value into x | yes: p = &y |
| Syntax | used like the object: r + 1 | needs *p and p->member |
| Arithmetic | no | yes: p + 1 |
| Arrays and containers of them | no arrays of references; std::vector<int&> is not allowed | allowed |
Typical uses
- `const T&` parameters: pass big objects without copying and without allowing changes. Example:
void print(const std::string &s). - `T&` parameters: the function is meant to modify the caller's object, as in
void swap(int &a, int &b). - Returning a reference to something that outlives the call, such as
vector::operator[]returningT&so thatv[i] = 5works. Never return a reference to a local variable: it dangles. - Pointers: when "no object" is a valid state (
nullptr), when you need to point to different objects over time, or for C APIs and low-level data structures.
Under the hood a reference is often implemented as a pointer, but the language gives no way to see that. It is not an object of its own, so sizeof(r) gives the size of the referenced type.
C++11 rvalue references (`T&&`) bind to temporaries. They make move semantics possible. That is a common follow-up question.
Original UniCircle question. Last reviewed 22 Oct 2026.
