Interview Q&A · C++ · 10 questions in this topic

Tricky Outputs & Gotchas — C++ Interview Q&A

All C++ topics

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

Example.cppcpp
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

Example.cppcpp
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

Example.cppcpp
struct Base { ~Base() {} }; // non-virtual!
struct D : Base { std::string big; };
Base* p = new D();
// delete p; // UB: D::~D never runs

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits