C++ interview preparation

C++ Interview Questions

Selected C++ interview questions for backend developers, grouped by topic and rendered from the same question catalog that powers EngineerSpeak practice.

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

Resource Management

1Explain RAII and how it shapes exception-safe resource management in C++ backend services.

RAII (Resource Acquisition Is Initialization) means a C++ object owns a resource and releases it from its destructor. Because local objects are destroyed automatically when their lifetime/scope ends, including during exception stack unwinding, RAII gives deterministic cleanup and makes error paths exception-safe. In backend services this applies not only to memory but also to file descriptors, sockets, mutex locks, database handles, transactions, and other OS or application resources.

class Fd {
public:
    explicit Fd(int fd = -1) noexcept : fd_(fd) {}
    ~Fd() { if (fd_ != -1) ::close(fd_); }

    Fd(const Fd&) = delete;
    Fd& operator=(const Fd&) = delete;

    Fd(Fd&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {}
    Fd& operator=(Fd&& other) noexcept {
        if (this != &other) {
            if (fd_ != -1) ::close(fd_);
            fd_ = std::exchange(other.fd_, -1);
        }
        return *this;
    }

    int get() const noexcept { return fd_; }

private:
    int fd_;
};

void handle_request() {
    Fd sock(::accept(...));
    if (sock.get() == -1) throw std::runtime_error("accept failed");
    // If any later operation throws, sock is still closed by ~Fd().
}
Try answering this question with an AI coach

Memory Management

2Compare std::unique_ptr and std::shared_ptr and describe when each is appropriate in backend APIs.

Prefer unique_ptr when one component owns the object: it destroys the resource on scope exit and transfers ownership explicitly by move. Use shared_ptr only when independent owners genuinely need to extend the same lifetime; its control block and reference counting add cost and can make destruction timing less obvious. weak_ptr observes a shared-owned object without owning it, useful for back-references or caches. Call lock to obtain a temporary shared_ptr and test whether the object still exists. Shared ownership cycles keep objects alive, so break appropriate edges with weak_ptr or redesign ownership. Reference-count safety does not make the pointee's mutable state thread-safe. Do not build unrelated shared_ptr control blocks from the same raw pointer, and do not transfer ownership through raw pointers accidentally. Use references or non-owning pointers for ordinary borrowing, and make ownership explicit in service interfaces.

struct Session {};

std::unique_ptr<Session> create_session();      // caller receives ownership
void process(Session& s);                       // borrows, does not own
void maybe_process(const Session* s);           // nullable borrow

class Dispatcher {
public:
    void add(std::shared_ptr<Session> s) {      // Dispatcher shares lifetime
        sessions_.push_back(std::move(s));
    }
private:
    std::vector<std::shared_ptr<Session>> sessions_;
};
Try answering this question with an AI coach

3What does an OS segmentation fault indicate, and what information would distinguish an invalid pointer from stack exhaustion?

On a typical Unix-like system, a segmentation fault means the process attempted a memory access that the OS could not permit, such as reading unmapped memory, writing a read-only page or executing a nonexecutable page. It is a symptom, not a diagnosis. I would inspect a symbolized core dump or debugger stop: the faulting instruction, access type, address, registers, memory mappings and thread stack. A null or obviously corrupted address, or an address from freed storage, points toward pointer/lifetime problems. A stack pointer near a guard page with many repeated recursive frames or unusually large local allocations suggests stack exhaustion. Stack corruption can mimic either case, and the damaging write may have occurred much earlier than the crash. Address/undefined-behavior sanitizers, reduced reproductions and allocation/lifetime tracing help find the original defect rather than merely suppress the failing instruction.

Try answering this question with an AI coach

4Explain 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

Type System

5How do C++ references and pointers differ in initialization, reassignment and absence of a target?

An ordinary C++ reference must bind to a suitable object when initialized and cannot later be reseated. Given int& r = a, writing r = b assigns b's value to a; it does not make r refer to b. A pointer is an object holding an address, so it can be reassigned to another target and can explicitly hold nullptr. A valid reference has no null state, whereas a pointer is useful for an optional target. This does not mean references guarantee lifetime: both references and pointers can dangle if the referred-to object dies. Neither a raw pointer nor a reference inherently owns its target. I use references for required borrowed objects, pointers for optional borrowed objects, and ownership types where lifetime responsibility must be represented.

Try answering this question with an AI coach

6Describe const-correctness in C++ APIs and how to design const member functions effectively.

Const-correctness means expressing through the type system which operations do not modify an object's observable or logical state. A const member function has a const-qualified this object, so it cannot modify non-mutable data members or call non-const member functions on the same object. Good API design marks read-only queries const, returns values or const references/pointers when appropriate, and avoids exposing mutable internal state from const functions. mutable should be reserved for implementation details that do not change logical state, such as caches, lazy values, metrics, or mutexes. const is an API contract about mutation, not an automatic guarantee of thread safety; concurrency guarantees need separate implementation and documentation.

#include <mutex>
#include <optional>
#include <string>

class UserProfile {
public:
    const std::string& id() const { return id_; }

    std::string displayName() const {
        std::lock_guard<std::mutex> lock(mu_);
        if (!cached_display_name_) {
            cached_display_name_ = computeDisplayName();
        }
        return *cached_display_name_;
    }

private:
    std::string computeDisplayName() const { return id_; }

    std::string id_;
    mutable std::mutex mu_;
    mutable std::optional<std::string> cached_display_name_;
};
Try answering this question with an AI coach

7What are move-only types and how do they influence API boundaries for sockets, file handles, and locks?

Move-only types are types that cannot be copied but can be moved. They are common for unique ownership of resources such as sockets, file descriptors, file handles, locks, and `std::unique_ptr`. Copy operations are deleted to avoid duplicated ownership and double release; move operations transfer ownership and leave the source valid but usually empty/non-owning. APIs should make ownership boundaries explicit: factories can return move-only objects by value, functions that take ownership can accept by value or rvalue reference, and functions that only inspect should take references, pointers, or other borrowing handles. Containers can store move-only values when elements are inserted or relocated by move.

#include <utility>

class Fd {
public:
    explicit Fd(int fd = -1) noexcept : fd_(fd) {}
    ~Fd() { close_if_valid(); }

    Fd(const Fd&) = delete;
    Fd& operator=(const Fd&) = delete;

    Fd(Fd&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {}

    Fd& operator=(Fd&& other) noexcept {
        if (this != &other) {
            close_if_valid();
            fd_ = std::exchange(other.fd_, -1);
        }
        return *this;
    }

    int get() const noexcept { return fd_; }
    explicit operator bool() const noexcept { return fd_ != -1; }

private:
    void close_if_valid() noexcept {
        if (fd_ != -1) {
            // ::close(fd_); // real POSIX code would close here
            fd_ = -1;
        }
    }

    int fd_;
};

Fd open_socket();               // factory returns ownership by value
void take_socket(Fd fd);        // takes ownership
void inspect_socket(const Fd&); // borrows only

void example() {
    Fd s = open_socket();
    inspect_socket(s);
    take_socket(std::move(s));
}
Try answering this question with an AI coach

8Compare 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

Object Lifetime

9How 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

Language Semantics

10Describe C++ initialization forms and common pitfalls, including initializer_list and aggregates.

C++ has several initialization forms. Default initialization, such as `T x;`, calls a default constructor for class types but leaves automatic fundamental variables uninitialized. Value initialization, such as `T x{};` or `T()`, zero-initializes where applicable before constructor/member initialization. List initialization uses braces, rejects narrowing conversions, and has special overload resolution rules, including strong preference for viable `std::initializer_list` constructors. Aggregate initialization initializes aggregate members directly with braces; C++20 also supports designated initializers for aggregates, in declaration order. Common pitfalls include uninitialized local scalars, surprising `initializer_list` overload selection, narrowing errors with braces, the most-vexing parse with parentheses, and behavior changes when a type stops being an aggregate.

#include <iostream>

struct S {
    int x;
};

int main() {
    int a;      // default-initialized: indeterminate value
    int b{};    // value/list-initialized: zero
    S s{};      // aggregate/value initialization: s.x is zero

    std::cout << b << ' ' << s.x << '\n';
    (void)a;    // reading a would be undefined behavior
}
Try answering this question with an AI coach

11What 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

Object Model

12Explain virtual functions, vtables, dynamic dispatch cost, object slicing, and virtual destructor hazards.

A virtual function enables runtime polymorphism: when called through a base pointer or reference, the implementation for the object's dynamic type is selected. Most implementations store a hidden vptr in each polymorphic object pointing to a vtable of virtual function addresses for that dynamic type. The typical cost is an extra pointer in the object, an indirect call, possible cache/branch-prediction impact, and reduced inlining opportunities, although compilers can sometimes devirtualize. Object slicing occurs when a derived object is copied or stored by value as a base object, losing the derived part and dynamic behavior. If a base class is meant to be deleted through a base pointer, its destructor must be virtual; otherwise deleting a derived object through that base pointer has undefined behavior.

#include <iostream>

struct Handler {
    virtual void handle() { std::cout << "base\n"; }
    virtual ~Handler() = default;
};

struct HttpHandler : Handler {
    void handle() override { std::cout << "http\n"; }
};

void run(Handler& h) {
    h.handle(); // virtual dispatch
}

int main() {
    HttpHandler h;
    run(h);
}
Try answering this question with an AI coach

Standard Library

13How would you implement the main operations of a vector-like container in C++?

Track allocated capacity separately from the number of constructed elements. Allocate suitably aligned raw storage, construct/destroy only live elements, and grow geometrically to obtain amortized constant push-back. On reallocation, track successful constructions and clean partial new storage on failure. Copy when needed to preserve the strong guarantee if copying exists and move may throw; a noncopyable type with a throwing move may limit the guarantee. Commit pointer/size/capacity only after successful transfer and document iterator invalidation.

Try answering this question with an AI coach

14Describe std::format and modern formatting facilities compared to iostreams and printf-style APIs.

`std::format` is the C++20 type-safe formatting facility inspired by fmtlib. It uses `{}` replacement fields and format specifications to produce formatted text without iostreams' stateful insertion syntax or `printf`-style C varargs. Compared with `printf`, it avoids many format/type mismatch problems; compared with iostreams, it is often clearer and easier to compose. fmtlib is the widely used library that preceded and influenced `std::format` and may provide broader support or newer features. User-defined types can be formatted with custom formatter support. In high-volume logging, performance depends on avoiding unnecessary formatting, conversions, and allocations, especially for disabled log levels; APIs that defer formatting or check log level first are preferable.

#include <format>
#include <string>

std::string msg = std::format("user={} latency_ms={:.2f}", user_id, latency_ms);
Try answering this question with an AI coach

Templates

15Explain 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

Concurrency

16How would you coordinate N C++ threads so they repeatedly emit their IDs in a fixed cyclic order?

Protect a turn index and stop flag with one mutex. Each worker waits on a condition variable until stopping or turn equals its ID, emits while preserving that order, advances turn modulo N, and calls notify_all so the eligible worker can proceed. Predicate waits handle spurious wakeups. Define iteration limits and failure behavior, and set the stop flag and wake all waiters on shutdown. Join workers before destroying shared state.

Try answering this question with an AI coach

17Explain condition_variable usage patterns for waiting on state changes.

Use `std::condition_variable` to wait for a mutex-protected state predicate to change. The shared state is modified while holding the same mutex, then `notify_one` or `notify_all` wakes waiters. Waiters should use `cv.wait(lock, predicate)` or an equivalent loop because wakeups can be spurious and notifications are not remembered independently of the predicate state. `notify_one` wakes one waiter; `notify_all` wakes all waiters and is appropriate for broadcast state changes such as shutdown.

std::mutex m;
std::condition_variable cv;
std::queue<int> q;
bool closed = false;

void push(int x) {
    {
        std::lock_guard<std::mutex> lk(m);
        q.push(x);
    }
    cv.notify_one();
}

std::optional<int> pop() {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, [&] { return !q.empty() || closed; });

    if (q.empty()) return std::nullopt; // closed and drained
    int x = q.front();
    q.pop();
    return x;
}

void close() {
    {
        std::lock_guard<std::mutex> lk(m);
        closed = true;
    }
    cv.notify_all();
}
Try answering this question with an AI coach

18Design a thread-safe bounded queue using standard C++ primitives and define its API guarantees.

A bounded thread-safe queue can be built with a `std::mutex`, condition variables, a fixed-capacity container, and a shutdown/closed flag. `push` blocks, times out, or fails when the queue is full, which provides backpressure; `pop` blocks when empty. Both operations should wait on predicates such as `size < capacity || closed` and `!empty || closed`. On shutdown/close, wake blocked producers and consumers; reject new pushes and define whether consumers drain existing items or immediately stop. The API should specify blocking behavior, close semantics, return values, and concurrency guarantees.

template<class T>
class BoundedQueue {
public:
    explicit BoundedQueue(std::size_t cap) : cap_(cap) {}

    // Returns false if the queue has been closed before the item is accepted.
    bool push(T value) {
        std::unique_lock<std::mutex> lk(m_);
        not_full_.wait(lk, [&] { return q_.size() < cap_ || closed_; });
        if (closed_) return false;

        q_.push_back(std::move(value));
        lk.unlock();
        not_empty_.notify_one();
        return true;
    }

    // Returns nullopt when closed and drained.
    std::optional<T> pop() {
        std::unique_lock<std::mutex> lk(m_);
        not_empty_.wait(lk, [&] { return !q_.empty() || closed_; });
        if (q_.empty()) return std::nullopt;

        T value = std::move(q_.front());
        q_.pop_front();
        lk.unlock();
        not_full_.notify_one();
        return value;
    }

    void close() {
        {
            std::lock_guard<std::mutex> lk(m_);
            closed_ = true;
        }
        not_empty_.notify_all();
        not_full_.notify_all();
    }

private:
    const std::size_t cap_;
    std::mutex m_;
    std::condition_variable not_empty_;
    std::condition_variable not_full_;
    std::deque<T> q_;
    bool closed_ = false;
};
Try answering this question with an AI coach

Database

19How do you execute a schema migration for a C++ service without downtime?

Use a staged expand-contract migration. First make backward-compatible schema additions, such as nullable columns or new tables, that do not break the currently running C++ service. Deploy compatible code that can handle both old and new representations, backfill existing data in small throttled batches, validate consistency, switch reads to the new schema, and only later remove old columns or code after all deployed versions no longer depend on them. For large tables, avoid long blocking DDL, use online/concurrent operations where supported, monitor locks/replication/resources, and keep rollback paths that work with partially deployed code and partially migrated data.

1. Expand: add new nullable column user_display_name.
2. Deploy compatible code: write both name and user_display_name; read new if present, else old.
3. Backfill: copy name -> user_display_name in small batches.
4. Validate: compare counts/checksums/null rates and monitor errors.
5. Switch: read only user_display_name after confidence.
6. Contract: stop writing old name, then drop old column in a later release.
Try answering this question with an AI coach

20How should a C++ service read from database replicas while managing stale reads and read-your-writes guarantees?

Treat replica reads as an explicit consistency trade-off. Reads that can tolerate staleness may go to healthy replicas, but read-your-writes, transactional, or freshness-critical reads should go to the primary unless the chosen replica is known to have replayed the relevant write position, such as an LSN, timestamp, or version. Track replica lag and health, encode the required consistency per endpoint or request, and fall back to primary, wait for catch-up, or fail when replicas exceed the allowed staleness. Document the consistency model so callers know which reads may be stale.

ReadPolicy EVENTUAL(max_staleness=2s):
  choose healthy replica with lag <= 2s; else primary or error depending on SLA

ReadPolicy READ_YOUR_WRITES(session_lsn):
  choose replica only if replay_lsn >= session_lsn;
  otherwise wait briefly or route to primary

ReadPolicy STRONG:
  route to primary
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