1.What is the difference between a pointer and a reference?
Show hint
Can either of them be null? Can either be changed to refer to something else?
Show solution
- A reference is another name for an existing object. It must be initialized, cannot be null, and cannot be re-seated.
- A pointer stores an address. It can be
nullptr, can be changed to point elsewhere, and needs*or->to reach the object.
int x = 10;
int& r = x; // r IS x
int* p = &x; // p holds x's address
r += 1; // x == 11
*p += 1; // x == 12Prefer references for parameters that must refer to a valid object, and pointers when "no object" (nullptr) is a valid value.