Two ways to refer to an existing object
A reference is an alias bound to an object. A pointer is an object that stores an address and can represent “no object” with nullptr. Choose references when a valid object is required, and pointers when optional or reseatable observation is part of the interface.
Observe the difference
#include
void increment(int& value) { ++value; }
int main() {
int score{10};
int& alias = score;
int* pointer = &score;
increment(alias);
*pointer += 4;
std::cout << score << '\n';
int other{50};
pointer = &other;
alias = other;
std::cout << score << ' ' << *pointer << '\n';
} Expected lines: 15 and 50 50. Assigning to alias changes score; it does not rebind the reference to other. Assigning &other to pointer changes the pointer's target without changing score.
Read-only parameters
void print(const std::string& text) accepts a string without copying it and prevents modification through that reference. It is useful for larger read-only values. Passing a small int by value is usually simpler. A const pointer target and a const pointer itself are different: const int* p restricts writes to the target, while int* const p restricts reseating p.
Lifetime still matters
A reference does not keep an arbitrary referred-to object alive indefinitely. Returning a reference or pointer to an automatic local creates a dangling result. A pointer into a vector can become invalid when the vector reallocates. Store and use borrowed access only while its target remains valid.
A reference cannot be validly bound by dereferencing nullptr. Saying “references are never null” is an interface expectation, not permission to create one from an invalid pointer. Use nullptr rather than the integer literal zero to express a null pointer in modern C++.
Exercises
- Write swap using two int& parameters. Starting at 3 and 8 should produce 8 and 3.
- Can
int& r;stand alone as a local declaration? No: it needs a binding initializer. - When would a pointer parameter make sense? For an optional object, with a documented nullptr case.
- Explain why the final assignment to alias in the example changes score instead of changing the reference relationship.