What is the fundamental difference between a reference and a pointer in C++? Can a reference be null?
Last updated
A reference is an alias for an existing object that must be bound at initialization and can never be rebound or be null; a pointer is an independent object holding an address that can be null, reassigned, and have arithmetic applied. No, a well-formed reference cannot be null.
Binding and reseating:
A reference must be initialized when declared and stays bound to that object for its lifetime.
A pointer can be left uninitialized, set to
nullptr, and pointed at different objects over time.
Nullability:
References have no null state in valid code; binding one to a dereferenced null pointer is undefined behavior.
Pointers explicitly model "no object" with
nullptr.
Syntax and semantics:
A reference is used like the object itself (no
*or->); pointers need dereferencing and support pointer arithmetic.Rule of thumb: use a reference when the object always exists, a pointer when absence or rebinding is meaningful.