Middle C++ preparation

Middle C++ Backend Interview Questions

15 selected Middle C++ interview questions for backend developers who need to discuss performance, ownership, and production trade-offs.

Start a Middle C++ AI InterviewNo credit card required. 1 free session available.
Technical interview practice in EnglishA mode where non-native speakers can practice passing technical interviews.

Memory Management

1How do automatic, static and dynamic storage duration differ in C++?

An ordinary block-local variable has automatic storage duration: its storage is associated with block execution, and a constructed object is normally destroyed when its scope exits, including exception unwinding. Namespace-scope variables and static locals have static storage duration, with storage lasting for the program; their initialization timing can differ, and destruction depends on successful construction and normal termination. Dynamic storage is obtained through allocation and persists until deallocation, independently of the allocating function's scope. I would normally manage it through containers or RAII owners such as unique_ptr rather than raw new/delete. Storage duration is not exactly object lifetime: storage can exist before construction or after destruction, as placement construction illustrates. A local unique_ptr itself can have automatic duration while its owned object has dynamic storage. 'Stack' and 'heap' are common implementation terms, not complete language definitions.

Try answering this question with an AI coach

2Explain weak_ptr and shared_ptr control-block mechanics, including cycles, enable_shared_from_this, and refcount costs.

A shared_ptr manages shared ownership through a control block containing strong and weak reference counts plus cleanup information such as the deleter and allocator. Copying or destroying shared_ptr objects increments or decrements the strong count, typically with atomic operations, so separate shared_ptr objects can be manipulated safely across threads but each refcount update has cost. When the strong count reaches zero, the managed object is destroyed; the control block remains until weak references are also gone. weak_ptr points to the same control block without extending object lifetime; lock() returns a shared_ptr if the object is still alive and an empty shared_ptr otherwise. Cycles made only of shared_ptr leak because strong counts never reach zero, so weak_ptr is used for back-pointers or observer links. enable_shared_from_this lets an object already owned by shared_ptr create a new shared_ptr to itself using the existing control block, avoiding dangerous separate control blocks. Refcount costs include atomic increments/decrements, cache contention, control-block allocation, and overhead in hot paths.

struct Parent;

struct Child {
    std::weak_ptr<Parent> parent; // non-owning back-reference
};

struct Parent {
    std::vector<std::shared_ptr<Child>> children; // owns children
};

void example() {
    auto p = std::make_shared<Parent>();
    auto c = std::make_shared<Child>();
    c->parent = p;
    p->children.push_back(c);

    if (auto locked = c->parent.lock()) {
        // safe use while Parent is still alive
    }
}
Try answering this question with an AI coach

Templates

3Explain C++ value categories and perfect forwarding, and why they matter for efficient generic APIs.

C++ value categories describe expressions: lvalues have identity and can be referred to after the expression; prvalues are pure rvalues such as many temporaries/computed values; xvalues are expiring objects whose resources may be reused. Perfect forwarding is the template technique of taking a forwarding reference, typically T&& where T is deduced, and forwarding with std::forward<T>(arg) so the caller's value category is preserved: lvalues remain lvalues and rvalues remain rvalues. Reference collapsing rules make this possible. It matters for generic backend APIs because wrappers, factories, dispatchers, and emplace-style functions can avoid unnecessary copies and preserve overload selection and move behavior.

#include <iostream>
#include <string>
#include <utility>

void sink(const std::string&) { std::cout << "const ref\n"; }
void sink(std::string&&) { std::cout << "rvalue ref\n"; }

template <class T>
void wrapper(T&& arg) {
    sink(std::forward<T>(arg));
}

int main() {
    std::string s = "hello";
    wrapper(s);
    wrapper(std::string{"x"});
}
Try answering this question with an AI coach

Type System

4Compare auto, decltype, decltype(auto), and template argument deduction in common backend code.

auto uses template-like deduction for variables: plain auto usually drops references and top-level const unless the declaration asks for them, such as auto&, const auto&, or auto&&. decltype(expr) inspects the declared type or expression type more exactly: an unparenthesized id-expression gives the declared type, while other lvalue expressions produce T&, xvalues produce T&&, and prvalues produce T. decltype(auto) deduces using decltype rules, often for return types when references must be preserved. Template argument deduction is similar to auto but depends on the parameter form, such as T, T&, const T&, or T&&, and has its own rules. Braced initializers are a common difference: auto x = {1,2} deduces std::initializer_list<int>, while a plain template parameter generally cannot deduce T from a bare braced initializer unless the parameter expects an initializer_list or another suitable type.

int x = 1;
const int cx = 2;
int& rx = x;

auto a = rx;        // int, copy of x
auto b = cx;        // int, top-level const dropped
const auto& c = cx; // const int&, reference preserved by declaration

a = 10;             // does not change x
Try answering this question with an AI coach

5Compare std::variant with inheritance-based polymorphism for modeling heterogeneous messages or events.

std::variant is a value type that holds exactly one alternative from a fixed, closed set of types and is commonly handled with std::visit or explicit type queries. It is useful for protocol messages or events when the set of message kinds is known and you want type-safe handling without virtual dispatch and often without per-object heap allocation. Inheritance-based polymorphism uses a base class and virtual functions to dispatch through a common interface; it is better when the set of derived message types is open, independently extensible, plugin-like, or hidden behind a stable interface. Variant favors closed sum types, locality, and compile-time checking; inheritance favors extensibility, runtime polymorphism, and interface-based design.

struct UserCreated { std::string id; };
struct UserDeleted { std::string id; };
struct PasswordChanged { std::string id; };

using Event = std::variant<UserCreated, UserDeleted, PasswordChanged>;

void handle(Event const& e) {
    std::visit([](auto const& msg) {
        using T = std::decay_t<decltype(msg)>;
        if constexpr (std::is_same_v<T, UserCreated>) {
            // handle creation
        } else if constexpr (std::is_same_v<T, UserDeleted>) {
            // handle deletion
        } else if constexpr (std::is_same_v<T, PasswordChanged>) {
            // handle password change
        }
    }, e);
}
Try answering this question with an AI coach

Language Semantics

6What is undefined behavior in C++, and how can it appear in backend production incidents?

Undefined behavior is behavior for which the C++ standard imposes no requirements after an invalid operation occurs. The program may appear to work, crash, corrupt data, expose security bugs, or be optimized into surprising behavior. Compilers assume UB does not happen and optimize based on that assumption, so issues may appear only in release builds or under production traffic. Backend incidents can come from dangling pointers/references, use-after-free, object lifetime violations, out-of-bounds access, signed integer overflow, data races, invalid casts, uninitialized reads, double frees, or strict-aliasing violations. Mitigation includes RAII and clear ownership/lifetime design, safer abstractions and bounds checks, testing/fuzzing, code review, static analysis, and sanitizers such as ASan, UBSan, and TSan.

int grow(int x) {
    if (x + 1 < x) {
        return 0; // compiler may assume this is unreachable
    }
    return x + 1;
}
Try answering this question with an AI coach

7Differentiate undefined, unspecified, and implementation-defined behavior with backend-relevant examples.

Undefined behavior means the C++ standard imposes no requirements; results may include crashes, data corruption, security bugs, or optimizer-dependent miscompilation. Examples include out-of-bounds access, use-after-free, signed integer overflow, and data races. Unspecified behavior means the standard allows more than one outcome and the implementation does not have to document which one is chosen; a common example is the evaluation order of many function arguments, so code should not depend on side effects being evaluated in a particular order. Implementation-defined behavior means the implementation must choose and document the behavior; examples include the signedness of plain `char`, sizes/ranges of some fundamental types within standard limits, and, in versions before C++20, right-shifting a negative signed value. Since C++20, valid signed right shifts are arithmetic (division by a power of two rounded toward negative infinity); invalid shift counts still cause undefined behavior. In backend code, UB is a correctness/security risk, while unspecified and implementation-defined behavior are portability risks that should be avoided or isolated in protocol, storage, and cross-platform logic.

int i = 0;
f(i++, i++); // both increments happen, but the order of argument evaluation is unspecified

// Prefer:
int a = i++;
int b = i++;
f(a, b);
Try answering this question with an AI coach

Error Handling

8A crash dump contains a program counter, stack pointer and stack memory. How would you reconstruct the call chain when frame pointers may be omitted?

I would obtain the exact executable and libraries, build IDs, load addresses, and matching debug/unwind information for the dump. Starting from the captured program counter and stack pointer, an unwinder uses ABI-specific call-frame rules, such as DWARF CFI or platform unwind tables, to recover the caller's stack position, return address, and saved registers. This can work without a dedicated frame pointer. A PC/SP-only dump may be insufficient when rules require other registers, so preserve the full register set where possible. Inline functions and tail calls complicate the distinction between logical and physical frames. If metadata is missing, disassembly and stack scanning can suggest candidates, but arbitrary values resembling code addresses are not a trustworthy call chain. Mark uncertainty and stop on corruption rather than presenting guessed frames as certain.

Try answering this question with an AI coach

9Explain std::expected or equivalent outcome types as alternatives to exceptions for fallible operations.

`std::expected<T, E>` represents either a successful value `T` or an explicit error `E`, making failure part of the function’s return type instead of relying on exception propagation. It is useful for fallible operations where errors are expected and callers should handle them locally, such as parsing, validation, network calls, storage lookups, and retryable backend operations. The error type should carry structured information such as an error code, category, retryability, message, or HTTP/RPC mapping. Expected/outcome types compose by checking and propagating errors, and in C++23-style APIs can use monadic operations such as `and_then`, `transform`, and `or_else` to chain steps without deeply nested conditionals. Compared with exceptions, they make control flow and API contracts explicit and support explicit error propagation in exception-free designs. std::expected is not itself a portable C or stable cross-toolchain ABI: use a defined boundary representation, and note that contained operations or value() on an error can still throw; exceptions may still be appropriate for rare, non-local, or truly exceptional failures depending on project policy.

enum class Errc { BadRequest, NotFound, Timeout, DbUnavailable };

struct Error {
    Errc code;
    bool retryable;
    std::string message;
};

std::expected<User, Error> load_user(UserId id);

HttpResponse handle(UserId id) {
    auto user = load_user(id);
    if (!user) {
        switch (user.error().code) {
            case Errc::BadRequest: return {400, user.error().message};
            case Errc::NotFound: return {404, "not found"};
            case Errc::Timeout: return {503, "try again"};
            case Errc::DbUnavailable: return {503, "service unavailable"};
        }
    }
    return {200, serialize(*user)};
}
Try answering this question with an AI coach

Object Lifetime

10What gets destroyed if a C++ constructor throws after initializing some members?

During unwinding of an ordinary non-delegating constructor, already fully constructed base and member subobjects are destroyed in reverse order of completed construction. The complete object's destructor is not called because its construction did not finish. If a member's own constructor throws, that member's destructor does not run, although its successfully constructed subobjects are unwound. Constructed local RAII objects are also cleaned up. A raw pointer member does not delete its pointee automatically, so owning resources should be wrapped in RAII types such as unique_ptr or containers before later throwing work. If a new-expression's construction fails, the appropriate matching deallocation function is normally invoked for that object's allocated storage; this does not rescue unrelated raw allocations. A qualification is delegating construction: if the target constructor completed and the delegating constructor body then throws, the object's destructor is invoked. Destructors used during unwinding should not let another exception escape.

Try answering this question with an AI coach

11Describe static initialization order issues and how constinit, magic statics, and dependency injection mitigate them.

Static initialization order issues occur because dynamically initialized namespace-scope or static objects in different translation units have unspecified relative initialization order. One global may use another before it has been constructed; destruction order can also create similar problems at shutdown. constinit forces a static or thread-local variable to have static/constant initialization or the program is ill-formed, avoiding dynamic initialization-order dependence for that variable. Magic statics, or function-local statics, are initialized on first use and are thread-safe since C++11. Dependency injection avoids hidden global dependencies by constructing objects in a controlled order and passing dependencies explicitly.

// a.cpp
extern std::string configPath;
Logger logger(configPath); // may run before configPath is dynamically initialized

// b.cpp
std::string configPath = readConfigPath();
Try answering this question with an AI coach

12What are copy elision, NRVO, and RVO, and when can you rely on them?

Copy elision means constructing an object directly in its final destination instead of creating a separate temporary and copying or moving it. RVO usually refers to returning an unnamed temporary or prvalue such as return T{}; in C++17 and later many of these cases are mandatory because the prvalue initializes the result object directly. NRVO is returning a named local object such as return x; the compiler is allowed to construct that local directly in the caller's return slot, but this is not guaranteed. You can rely on mandatory C++17 prvalue elision in the specified cases, but not on NRVO always happening; avoid std::move on a named local return value because it can prevent NRVO.

struct T {
    T();
    T(const T&) = delete;
    T(T&&) = delete;
};

T make() {
    return T{}; // OK in C++17+: result object is constructed directly
}
Try answering this question with an AI coach

Standard Library

13Given an array and a deterministic key function, how would you group elements with equal keys in expected linear time?

Compute each key once and append each element to its group in a hash map. The expected bound assumes constant key computation and hashing. Track first-seen keys separately if group order matters.

Try answering this question with an AI coach

14You must order records with many equal keys. When would merge sort be preferable to a typical in-place quicksort, and what would you give up?

Merge sort is preferable when records with equal keys must preserve their original relative order, such as keeping an earlier secondary ordering after sorting by a primary field. A standard stable merge implementation provides that guarantee and O(N log N) worst-case time. Typical in-place quicksort is unstable and can have quadratic worst cases, although good pivoting and three-way partitioning handle many equal keys well. Therefore duplicates alone do not prove that every quicksort implementation will be slow. For arrays, conventional merge sort usually needs O(N) auxiliary storage and extra copying or moves, while in-place quicksort generally uses less additional storage apart from its stack. Linked-list merge sort has different storage characteristics. I would choose based on stability, worst-case requirements, memory budget, and the actual implementation rather than algorithm names alone.

Try answering this question with an AI coach

Concurrency

15Explain the C++ memory model: data races, happens-before, and synchronization guarantees.

The C++ memory model defines when operations in different threads are ordered and when writes become visible. A data race occurs when two threads access the same memory location concurrently, at least one access is a write, and the accesses are not ordered by happens-before or otherwise made safe by atomic operations; a data race causes undefined behavior. Happens-before is the ordering relation that makes earlier side effects visible to later operations. Synchronization operations create this ordering: for example, unlocking a mutex synchronizes-with a later successful lock of the same mutex, and suitable atomic release/acquire operations can synchronize between threads. Correct programs use mutexes, atomics, or other synchronization to establish happens-before for shared state.

std::mutex m;
int x = 0;

void producer() {
    std::lock_guard<std::mutex> lk(m);
    x = 42;
} // unlock

void consumer() {
    std::lock_guard<std::mutex> lk(m); // lock after producer unlock synchronizes-with it
    std::cout << x << '\n';
}
Try answering this question with an AI coach

Practice C++ interviews on your phone

Answer out loud and get AI feedback in the Android app.

Get EngineerSpeak on Google Play
Scan to download