Interview Q&A · C++ · 10 questions in this topic
Pointers vs References — C++ Interview Q&A
The heart of C++ interviews — pointers, references, const correctness, dangling, and ownership thinking. Part of Pointers, References & RAII · 213 questions in the C++ bank.
What is the difference between a pointer and a reference?
Answer
A pointer holds an address: it can be null, reseated, and needs explicit dereference (*p). A reference is an alias: it must bind at initialization, cannot be null or reseated, and is used with plain value syntax.
Guideline: references for required aliases (parameters, range-for), pointers for optional/reseatable indirection and C interop.
Key points
- 1Null — pointers yes, references no (a null reference is UB).
- 2Reseat — pointers yes (p = &other), references no.
- 3Syntax — pointers use -> and *, references use . directly.
Example
int x = 1, y = 2; int* p = &x; p = &y; // reseated, fine int& r = x; // r aliases x forever // int& bad; // error: must initialize
💡 Must-bind-once plus cannot-reseat is the complete reference contract in one line.
What is const correctness and what do the const positions on pointers mean?
Answer
Const correctness uses the type system to forbid mutation mistakes: const member functions, const references, const pointers. Reading right-to-left decodes pointer consts: `const int*` is pointer-to-const (cannot change the pointee), `int* const` is const-pointer (cannot reseat), `const int* const` is neither.
East-const style (`int const*`) reads uniformly right-to-left and avoids the single exception in west-const parsing.
Example
const int* a; // pointee is const (reseat ok) int* const b = nullptr; // pointer is const (reseat banned) // const int* const c; // both const void read(const std::string& s); // const-correct in-param
💡 Read pointer declarations right-to-left out loud — interviewers accept that as the decoding method.
What is a dangling pointer/reference and how do dangling bugs happen?
Answer
A dangling pointer/reference points at storage whose lifetime ended — a destroyed stack local, a deleted heap object, a reallocated vector element, or a temporary that died at the semicolon. Using it is undefined behavior that may appear to work until optimization or reuse exposes it.
Common factories: returning locals by reference/pointer, storing string_view/c_str views past owner death, holding iterators across vector reallocation, and use-after-free.
Example
int& bad() { int local = 1; return local; // dangling: local dies at return } std::string_view v; { std::string s = "hi"; v = s; } // s dies; v dangles
What is the difference between stack and heap allocation?
Answer
Stack (automatic storage) is scope-managed: allocation is a pointer bump, destruction is automatic and deterministic — fast and exception-safe. Heap (dynamic storage) lives until explicitly freed or owned: flexible lifetime and size, but manual management, fragmentation risk and slower allocation.
Modern C++ keeps values on the stack by default and puts heap ownership inside RAII owners (containers, strings, smart pointers) so raw new/delete rarely appears.
Key points
- 1Lifetime — stack ends at scope exit; heap ends at delete/owner death.
- 2Speed — stack bump vs heap allocator bookkeeping.
- 3Safety — stack is exception-safe by construction; heap needs RAII owners.
Example
void f() { int stack_val = 1; // dies at } automatically auto owned = std::make_unique<int>(2); // heap int, freed automatically }
What is pointer arithmetic and why is it dangerous?
Answer
Pointer arithmetic (p+1, p++, p-q) moves in units of the pointed-to type and is only defined within (or one past) the same array object. Straying outside is undefined behavior; void* arithmetic is illegal (no size to scale by) and char* is the byte-level exception.
Modern code prefers iterators, spans and indexed access — same expressiveness with bounds-checked options.
Example
int a[4] = {10, 20, 30, 40}; int* p = a; // *(p + 2) == 30; // defined: inside the array // *(p + 100); // undefined behavior
💡 Within-or-one-past-the-same-array is the complete legality rule.
What is the difference between `*p`, `&x`, `int* p` and `int& r`?
Answer
Symbols change meaning by context: in a declaration, * introduces a pointer and & introduces a reference; in an expression, * dereferences a pointer and & takes an address. So `int* p = &x` reads as: declare p as pointer-to-int, initialize it with the address of x.
Candidates confuse declaration-meaning with expression-meaning under pressure — stating the context split resolves every variant.
Example
int x = 5; int* p = &x; // decl *: pointer; expr &: address-of int& r = x; // decl &: reference int y = *p; // expr *: dereference
What are lvalues, rvalues and forwarding references?
Answer
Value categories describe expressions: lvalues have identity and are addressable (named variables), prvalues are temporaries without identity, xvalues are expiring values with identity (std::move results). Lvalue references (T&) bind lvalues; rvalue references (T&&) bind rvalues and power move semantics. A T&& in a deduced template context is a forwarding reference that binds either and preserves the category with std::forward.
Move semantics steal from rvalues safely because the source is expiring; stealing from an lvalue requires an explicit std::move opt-in.
Example
int x = 1; // int&& a = x; // error: rvalue ref cannot bind lvalue int&& b = 5; // ok: binds temporary int&& c = std::move(x); // explicit opt-in to treat x as expiring
💡 Identity plus movability is the two-word summary: lvalues have names, rvalues are movable-from.
What is `nullptr` and why is it better than NULL or 0?
Answer
nullptr is the type-safe null pointer literal of type std::nullptr_t, convertible to any pointer type but to no integer type. NULL/0 are integers, so f(0) can surprise by selecting an int overload instead of a pointer overload; f(nullptr) always selects the pointer one.
Always use nullptr in modern code — it documents intent and fixes overload-resolution surprises.
Example
void f(int); void f(int*); // f(0); // calls f(int) — surprise! // f(NULL); // usually f(int) too f(nullptr); // calls f(int*) — correct
What is a void pointer and what can you (not) do with it?
Answer
void* is an untyped address: it can hold any object pointer and is the lingua franca of C APIs, but you cannot dereference it, do arithmetic on it, or delete through it without casting back to the real type. Round-tripping through void* and back is safe only with the exact original type.
C++ prefers type-safe alternatives (templates, std::any, std::variant, base interfaces) except at genuine C boundaries.
Example
int x = 42; void* v = &x; // ok: type erased // *v; // error: incomplete type int* back = static_cast<int*>(v); // exact-type round trip
What is strict aliasing and why does type-punning through pointers break?
Answer
The strict-aliasing rule lets the compiler assume differently-typed pointers do not alias the same memory (with narrow exceptions for char/unsigned char and similar types), enabling aggressive load/store optimization. Reinterpreting an int* as float* and reading through it violates the rule — undefined behavior that -fstrict-aliasing builds exploit.
Legal type punning uses memcpy, std::bit_cast (C++20), unions read-as-written, or char-pointer inspection.
Example
#include <bit> float f = 3.14f; // int i = *reinterpret_cast<int*>(&f); // UB: aliasing violation int i2 = std::bit_cast<int>(f); // ok (C++20)
💡 Say the fix (memcpy/bit_cast), not just the rule — interviewers want the safe alternative.
Recommended resourcesAffiliate links · may earn us a commission