Compare C++ Pointers and References
Company: Hudson
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Compare C++ Pointers and References
Compare C++ pointers and references. Explain initialization, nullability, reseating, syntax, arithmetic, ownership, const behavior, lifetime risks, and how the choice communicates an API contract.
### Constraints & Assumptions
- Discuss language-level behavior rather than assuming a particular machine representation.
- Neither a raw pointer nor a reference implies ownership by itself.
- Include dangling cases and the limits of using either type as a safety guarantee.
- Distinguish `const T*`, `T* const`, and `const T&` where useful.
### Clarifying Questions to Ask
- Is the comparison about function parameters, object members, iteration, or all uses?
- Should smart pointers, spans, and reference wrappers be considered as alternatives?
- Does a null or absent value belong in the domain?
- Is ownership transfer part of the API?
### Hints
- A reference must be bound when created, but it can still dangle later.
- Assignment through a reference assigns to the referred object; it does not rebind the reference.
- Pointer arithmetic is meaningful only within the permitted array-object rules.
### What a Strong Answer Covers
- Binding, nullability, reseating, dereference syntax, arithmetic, and storage representation caveats.
- Const qualification of the pointer versus the pointed-to object and const references.
- Lifetime and dangling risks for both forms.
- Raw non-owning use versus `unique_ptr`, `shared_ptr`, `weak_ptr`, `span`, and optional references by wrapper.
- API intent: required borrowed object, optional borrowed object, range, ownership transfer, or shared lifetime.
- Trade-offs for members, containers, polymorphism, and overload resolution.
### Follow-up Questions
1. Can a reference be null in a well-defined C++ program?
2. Why can returning a reference to a local variable compile but still be wrong?
3. When is `std::span` clearer than a pointer plus length?
4. Why is `shared_ptr` not a default replacement for every owning pointer?
Quick Answer: Compare C++ pointers and references across initialization, nullability, reseating, syntax, arithmetic, const qualification, and dangling risks. Use the distinction to communicate required borrowing, optional access, ranges, ownership transfer, or shared lifetime in an API.