Skip to content
LeetQuant
QD11 Quant Developer Interview Preparation

QD11 · Quant Developer Interview Preparation · Lesson 2 of 4

C++ Question Bank

Eighteen short C++ interview questions with crisp answers, each code-related answer backed by a program compiled with clang and run: destructors, move semantics, vector growth, undefined behaviour, const, inline, templates, smart pointers and memory ordering.

20 min

How these questions are asked

C++ questions in quant-developer interviews come in rapid bursts: "what is a virtual destructor for?", "what does std::move do?", "when does a vector reallocate?". The interviewer wants a one- or two-sentence precise answer, then checks depth with a follow-up. A good answer names the rule, gives the consequence, and, where it matters, says what the standard guarantees versus what one implementation happens to do.

Every program below was compiled with c++ -std=c++20 -O2 -Wall (Apple clang 17, libc++) and run; outputs are real. Where a result is implementation-specific, the answer says so.

Object lifetime and polymorphism

1. Why do polymorphic base classes need a virtual destructor? Deleting a derived object through a base pointer is undefined behaviour unless the base destructor is virtual. In practice the derived destructor is skipped, leaking whatever it owns.

2. Does shared_ptr<Base> need it too? Less than you think: shared_ptr<Base>(new Derived) records a deleter for Derived in its control block at construction, so it destroys correctly. unique_ptr<Base> calls delete on a Base* and does not. Still make the destructor virtual; relying on the shared_ptr quirk is fragile.

#include <cstdio>
#include <memory>
struct Base { ~Base() { std::puts("~Base"); } };
struct Derived : Base { ~Derived() { std::puts("~Derived"); } };
struct VBase { virtual ~VBase() { std::puts("~VBase"); } };
struct VDerived : VBase { ~VDerived() override { std::puts("~VDerived"); } };
int main() {
    std::puts("-- shared_ptr<Base>(new Derived)");
    { std::shared_ptr<Base> s(new Derived); }
    std::puts("-- unique_ptr<Base>(new Derived)");
    { std::unique_ptr<Base> u(new Derived); }   // undefined behaviour
    std::puts("-- unique_ptr<VBase>(new VDerived)");
    { std::unique_ptr<VBase> u(new VDerived); }
}
-- shared_ptr<Base>(new Derived)
~Derived
~Base
-- unique_ptr<Base>(new Derived)
~Base
-- unique_ptr<VBase>(new VDerived)
~VDerived
~VBase

3. What happens if a constructor calls a virtual function? It dispatches to the class currently being constructed, not the most-derived class, because the derived part does not exist yet. Constructing a Derived whose Base constructor calls hello() printed Base::hello. (Calling a pure virtual this way is undefined behaviour.)

4. What is the rule of zero / five? If a class manages a resource directly, define or delete all five special members (destructor, copy and move constructors, copy and move assignment). Better: hold resources in members that manage themselves (unique_ptr, vector) and define none of them (rule of zero).

Move semantics and copy elision

5. What does std::move do? Nothing at run time: it is a cast to an rvalue reference, which makes the object eligible to be moved from. Whether a move happens depends on overload resolution. std::move on a const object yields const T&&, which cannot bind to T&&, so the copy constructor is chosen.

6. What state is a moved-from object in? "Valid but unspecified" for standard library types: you may destroy it or assign to it, and calling functions without preconditions (like size()) is fine, but do not rely on its value. A long std::string on libc++ showed size 0 after the move; that is an implementation detail.

7. Why should move constructors be noexcept? std::vector must keep the strong exception guarantee when it reallocates. If the element's move constructor might throw (and the type is copyable), it copies instead (std::move_if_noexcept). Dropping noexcept silently turns every reallocation into copies.

#include <cstdio>
#include <string>
#include <utility>
#include <vector>
struct Tracer {
    Tracer() = default;
    Tracer(const Tracer&) { std::puts("copy"); }
    Tracer(Tracer&&) noexcept { std::puts("move"); }
};
struct NoexceptLess {
    NoexceptLess() = default;
    NoexceptLess(const NoexceptLess&) { std::puts("copy"); }
    NoexceptLess(NoexceptLess&&) { std::puts("move"); }   // not noexcept
};
int main() {
    const Tracer c;
    Tracer a = std::move(c);          // const rvalue binds to the copy ctor
    std::string s = "a string long enough to defeat the small string buffer";
    std::string t = std::move(s);
    std::printf("moved-from size: %zu, target size: %zu\n", s.size(), t.size());
    std::puts("-- vector<Tracer> growth 1->2");
    std::vector<Tracer> v; v.reserve(1); v.emplace_back(); v.emplace_back();
    std::puts("-- vector<NoexceptLess> growth 1->2");
    std::vector<NoexceptLess> w; w.reserve(1); w.emplace_back(); w.emplace_back();
    (void)a;
}
copy
moved-from size: 0, target size: 54
-- vector<Tracer> growth 1->2
move
-- vector<NoexceptLess> growth 1->2
copy

8. Is returning a local by value expensive? Usually free. Returning a prvalue (return T{};) is guaranteed elision since C++17. Returning a named local (T t; return t;) allows NRVO, which compilers do in practice but are not required to; if they do not, the return is an implicit move, never a copy. With two candidate locals (if (b) return x; return y;) NRVO is impossible and clang performed a move. Writing return std::move(t); is a pessimisation: it disables NRVO.

Containers

9. How does std::vector grow, and why geometrically? When size() == capacity(), it allocates a larger buffer (libc++ and libstdc++ double; MSVC grows by 1.5), moves or copies the elements and frees the old buffer. Geometric growth makes push_back amortised O(1)O(1): with doubling, building nn elements costs at most about 2n2n element moves in total. Growing by a constant would make it O(n)O(n) per push on average.

10. What invalidates vector iterators and references? Any reallocation invalidates all of them; insertion or erasure invalidates those at or after the point of change. reserve(n) up front guarantees no reallocation until the size exceeds nn. clear() keeps the capacity; shrink_to_fit() is a non-binding request.

#include <cstdio>
#include <vector>
int main() {
    std::vector<int> v;
    std::size_t last = v.capacity();
    std::printf("%zu", last);
    for (int i = 0; i < 1000; ++i) {
        v.push_back(i);
        if (v.capacity() != last) { last = v.capacity(); std::printf(" %zu", last); }
    }
    std::puts("");
    std::vector<int> r; r.reserve(100);
    int* p = r.data(); for (int i = 0; i < 100; ++i) r.push_back(i);
    std::printf("same buffer after reserve: %d\n", p == r.data());
    v.clear(); std::printf("after clear: size %zu capacity %zu\n", v.size(), v.capacity());
    v.shrink_to_fit(); std::printf("after shrink_to_fit: capacity %zu\n", v.capacity());
}
0 1 2 4 8 16 32 64 128 256 512 1024
same buffer after reserve: 1
after clear: size 0 capacity 1024
after shrink_to_fit: capacity 0

11. push_back or emplace_back? emplace_back constructs in place from constructor arguments; push_back(T) takes an existing object and moves or copies it. With an already-built object they are equivalent. emplace_back can call explicit constructors, which can hide mistakes (v.emplace_back(1000) on a vector<vector<int>> silently creates a 1000-element vector).

12. Why is a struct bigger than the sum of its members? Alignment padding. struct { char c; double d; char e; } is 24 bytes on a 64-bit target; reordering to { double d; char c; char e; } gives 16. Ordering members from largest to smallest alignment is the usual fix, and it matters for cache footprint in hot structures.

Undefined behaviour, const and inline

13. Why is signed overflow dangerous even if "it just wraps"? Signed overflow is undefined behaviour, so the optimiser assumes it never happens. bool f(int x) { return x + 1 > x; } is compiled to return true. Unsigned arithmetic is defined to wrap modulo 2n2^{n}, so the same function on unsigned returns false for the maximum value. The same program returned different answers at different optimisation levels:

-O2:  int: 1  unsigned: 0     (f(INT_MAX) folded to true)
-O0:  int: 0  unsigned: 0

Other UB to name quickly: out-of-bounds access, use after free, dereferencing null, data races, reading an uninitialised variable, violating strict aliasing, shifting by at least the bit width.

14. What does const on a member function mean, and what is mutable for? this becomes a pointer to const, so the function cannot modify members and can be called on const objects. mutable members (caches, hit counters, a mutex) may change anyway; a const Cache whose value() incremented a mutable int hits twice reported hits 2. A const member function should still be thread-safe to call concurrently, which is why a mutable cache usually needs a mutex or an atomic.

15. What does inline mean today? Not "please inline": compilers decide that themselves. It means the function (or, since C++17, variable) may be defined in several translation units, as long as the definitions are identical (the one-definition rule). A non-inline function defined in a header included by two .cpp files fails to link; marking it inline fixes it:

== plain header, two TUs
duplicate symbol 'mid(int, int)' in:
ld: 1 duplicate symbols
== inline header, two TUs
5 3

Functions defined inside a class body, templates and constexpr functions are implicitly inline, which is why they can live in headers.

Templates, smart pointers and memory ordering

16. Why must template definitions usually be in headers, and what do concepts add? A template is instantiated where it is used, so the compiler needs the definition in that translation unit (unless you explicitly instantiate the types you need in one .cpp). Concepts constrain parameters and give readable errors at the call site. Calling a template <Arithmetic T> T square(T) with a string literal produced:

error: no matching function for call to 'square'
note: candidate template ignored: constraints not satisfied [with T = const char *]
note: because 'const char *' does not satisfy 'Arithmetic'

17. unique_ptr, shared_ptr, weak_ptr: costs and pitfalls? unique_ptr with the default deleter is the size of a raw pointer (8 bytes here) and has no overhead; it is move-only. shared_ptr is two pointers (16 bytes: object and control block) and every copy does an atomic reference-count increment, so pass it by const reference unless you are sharing ownership. make_shared puts object and control block in one allocation. Two shared_ptrs pointing at each other never reach count zero: in the test, a two-node cycle had use_count 2 at scope exit and neither destructor ran. Making one link a weak_ptr broke the cycle and both destructors ran.

18. What do acquire and release guarantee? If thread A does writes and then a release store to an atomic, and thread B does an acquire load that reads that value, then all of A's writes before the store are visible to B after the load. This is the standard way to publish data:

#include <atomic>
#include <cstdio>
#include <thread>
int payload = 0;
std::atomic<bool> ready{false};
int main() {
    std::thread producer([] { payload = 99; ready.store(true, std::memory_order_release); });
    std::thread consumer([] {
        while (!ready.load(std::memory_order_acquire)) {}
        std::printf("consumer sees payload %d\n", payload);
    });
    producer.join(); consumer.join();
}
consumer sees payload 99

With memory_order_relaxed on both sides the program would contain a data race on payload (undefined behaviour), even though x86 hardware would usually make it appear to work; ARM would not. relaxed is right for a standalone counter whose value is not used to publish other data. seq_cst (the default) adds a single global order over all such operations and costs a full fence on x86 stores. And volatile is not a synchronisation tool in C++: it prevents the compiler eliding accesses (for memory-mapped I/O) but gives no atomicity or ordering between threads.

Worked example

answering a C++ question out loud

"We have std::vector<Quote> where Quote has a user-written move constructor. After profiling we see reallocation copying every element. Why, and what do you change?"

Show solution

Rule: vector reallocation uses std::move_if_noexcept; it moves only if the move constructor is noexcept (or the type is not copyable), to preserve the strong exception guarantee.

Diagnosis: the user-written move constructor is not marked noexcept, so the vector copies. (The NoexceptLess test above printed copy on growth; the noexcept version printed move.)

Fix, in order of preference: (1) if the members are themselves movable, delete the hand-written move constructor and let the compiler generate it; it is noexcept when all members' moves are. (2) Otherwise mark it noexcept if it cannot throw. (3) Independently, reserve the expected size so reallocation does not happen on the hot path. Add static_assert(std::is_nothrow_move_constructible_v<Quote>); so a future change cannot silently regress it.

That answer has the rule, the cause, a ranked fix and a guard, in under a minute.

Knowledge check

What does std::move(x) do when x is declared const std::string?

Knowledge check

A header defines a non-template, non-inline free function, and two .cpp files include it. What happens?

Knowledge check

One thread writes a struct and then sets an std::atomic<bool> flag; another spins on the flag and then reads the struct. What is the weakest correct ordering?

Key takeaways

  • Lead with the rule, then the consequence: "deleting through a base pointer without a virtual destructor is UB; the derived destructor is skipped".
  • std::move is a cast; noexcept on moves decides whether vector moves or copies; return std::move(local) disables NRVO.
  • Vector growth is geometric (amortised O(1)O(1) push), and any reallocation invalidates every iterator, pointer and reference.
  • Signed overflow is UB that the optimiser exploits; inline is about the one-definition rule, not speed.
  • Release/acquire publishes data between threads; relaxed is for standalone counters; volatile is not for threads.
  • Separate what the standard guarantees from what your compiler happened to do.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).