Interview Q&A · C++ · 10 questions in this topic
Tricky Outputs & Gotchas — C++ Interview Q&A
The prediction questions interviewers love — initialization, overloads, slicing, lifetimes and undefined behavior traps. Part of Tricky Outputs & Coding Tasks · 213 questions in the C++ bank.
What is the output of `int x[5];` vs `int x[5]{};` at function scope?
Answer
At function scope, int x[5]; leaves elements with indeterminate values (reading them is UB), while int x[5]{}; value-initializes every element to 0. At namespace scope both zero-initialize (static storage).
The braces are the difference between garbage and zeros — and reading garbage is UB, not merely unspecified.
Example
void f() { int a[3]; // indeterminate! int b[3]{}; // {0, 0, 0} }
Why does `std::vector<bool>` behave strangely?
Answer
vector<bool> is a bit-packed specialization, not a container of bools: operator[] returns a proxy reference, not bool&. Consequences: no real bool* data(), auto deduces the proxy (dangling if captured by reference carelessly), and generic code assuming Container<T>::reference is T& breaks.
Prefer std::vector<char>, std::deque<bool> or std::bitset/dynamic_bitset when you need real references or contiguous bools.
Example
std::vector<bool> v{true, false}; // bool* p = v.data(); // no such function! auto b = v[0]; // proxy object, NOT bool&
💡 Proxy reference instead of bool& is the one-line explanation.
What happens when you `delete` a derived object through a non-virtual base pointer?
Answer
Only the base destructor runs and the behavior is undefined — derived members leak (at best) and heaps corrupt (at worst). With a virtual destructor the full chain runs correctly.
Smart pointers do not save you: unique_ptr<Base> and shared_ptr<Base> share the same requirement.
Example
struct Base { ~Base() {} }; // non-virtual! struct D : Base { std::string big; }; Base* p = new D(); // delete p; // UB: D::~D never runs
Signed overflow, shift-out-of-range and divide-by-zero — which are UB?
Answer
All three are undefined behavior for signed integers: signed overflow wraps on no platform you may rely on, shifts by >= width or of negative values are UB, and division/modulo by zero traps. Unsigned arithmetic wraps modulo 2^N by definition (not UB), though still a logic bug if unintended.
Compilers exploit signed-overflow UB for optimization (loop induction, bounds checks), so -fwrapv-style assumptions break under -O2.
Example
int m = INT_MAX; // m + 1; // UB: signed overflow // 1 << 99; // UB: shift too far unsigned u = UINT_MAX; u + 1; // defined: wraps to 0
💡 Signed is UB, unsigned wraps — that pairing answers the whole family.
Why does `for (auto x : v) x++` not modify the vector?
Answer
auto deduces by value — x is a copy of each element, so increments die with the iteration. const auto& observes read-only; auto& mutates in place.
The same rule applies to structured bindings (auto [a,b] copies) and range variables generally.
Example
std::vector<int> v{1, 2, 3}; for (auto x : v) x++; // copies: v unchanged for (auto& x : v) x++; // references: v becomes {2,3,4}
What is the most vexing parse and how do you avoid it?
Answer
C++ parses Widget w(); as a function declaration (returns Widget, named w), not a default-constructed object. Brace initialization Widget w{}; constructs the object unambiguously (and bans narrowing).
Uniform braces plus auto (auto w = Widget{};) eliminate the whole class of mistakes.
Example
struct Widget { Widget(); }; // Widget w(); // declares a FUNCTION, not an object! Widget w{}; // an actual object Widget u; // also an object (no parens, no ambiguity)
💡 Declaration vs object is the surprise; braces are the fix.
Why do base-class overloads disappear when a derived class declares one overload?
Answer
Name lookup stops at the first scope containing the name — the derived declaration hides every base overload of that name, even with different signatures. Calls then convert (or fail) against the small visible set.
Restore with `using Base::f;` or qualify explicitly; prefer this fix over renaming overloads.
Example
struct Base { void f(int); void f(double); }; struct D : Base { void f(int); }; // hides f(double)! // D d; d.f(1.5); // converts to int — surprise
What is use-after-move? Is reading a moved-from object UB?
Answer
Use-after-move reads an object in a valid-but-unspecified state: not UB by itself (destruction/assignment are always safe), but any assumption about its value is a logic bug. Only operations with preconditions (dereference, front(), pop) become UB if the state no longer satisfies them.
Best practice: reset or reassign immediately after moving in non-trivial flows, and never branch on a moved-from value.
Example
std::string a = "hello"; std::string b = std::move(a); // std::cout << a; // valid code, unspecified output — do not rely on it a = "fresh"; // safe: reassigned before real use
💡 Valid-but-unspecified, not UB — that precision is the senior answer.
Why must `new[]` pair with `delete[]` (and what breaks otherwise)?
Answer
new[] stores the element count (cookie) for destructor calls; scalar delete does not read it — so destructors never run (leak) and the heap sees a mismatched header (corruption). The reverse (delete[] on scalar new) reads garbage as a count.
Modern code avoids the question: std::vector/array/string own dynamic sequences.
Example
std::string* p = new std::string[3]; // delete p; // UB: destructors skipped, heap corrupted delete[] p; // correct: all three destroyed
What does `static_cast`, `dynamic_cast`, `const_cast` and `reinterpret_cast` each do?
Answer
static_cast: well-defined conversions (numeric, downcast without check, void* round-trip). dynamic_cast: checked polymorphic navigation (null/throw on failure, needs RTTI). const_cast: adds/removes const (writing through it to a truly-const object is UB). reinterpret_cast: raw bit reinterpretation (pointer/int punning — narrow, dangerous).
C-style casts hide which of these you meant — always spell the specific cast.
Key points
- 1static — checked-at-compile conversions.
- 2dynamic — runtime-checked hierarchy moves.
- 3const — const adjustment only.
- 4reinterpret — bit-level retyping, last resort.
Example
const int ci = 5; // int& r = const_cast<int&>(ci); r = 6; // UB: truly const! float f = 1.5f; int bits = std::bit_cast<int>(f); // safe punning (C++20)
💡 Say which cast for which job and ban C-style casts — that is the complete casting doctrine.
Recommended resourcesAffiliate links · may earn us a commission