Junior C++ preparation

Junior C++ Backend Interview Questions

15 selected Junior C++ interview questions for backend developers who need to explain language fundamentals and basic ownership clearly.

Start a Junior 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.

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

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

Type System

3How can a C++ program determine the native byte order of its target?

Use std::endian::native in C++20. In older code, inspect the object representation of a fixed-width unsigned integer through unsigned char or memcpy. Define behavior for unusual targets and use explicit conversions in wire formats.

Try answering this question with an AI coach

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

5What is std::byte and how should raw binary buffers be represented safely in C++?

std::byte is a distinct type for representing raw binary data as bytes, not characters or arithmetic integers. It improves type safety because byte buffers are not accidentally treated as text or numeric values, while still supporting bitwise operations. Raw binary buffers should usually be represented with byte-oriented storage such as std::vector<std::byte> or std::array<std::byte, N>, and passed through non-owning APIs as std::span<std::byte> or std::span<const std::byte>. Serialization code should explicitly encode and decode values rather than relying on arbitrary object layouts.

void write_frame(std::span<const std::byte> payload);

std::vector<std::byte> buf;
buf.push_back(std::byte{0x01});
buf.push_back(std::byte{0xFF});
write_frame(buf);
Try answering this question with an AI coach

Object Lifetime

6Describe the Rule of Zero, Rule of Three, and Rule of Five and when each applies.

Rule of Zero: prefer classes that do not declare custom destructor/copy/move operations; let RAII members such as std::string, std::vector, std::unique_ptr, file/socket wrappers, etc. manage resources. Rule of Three: if a class manually manages a resource and needs a custom destructor, copy constructor, or copy assignment operator, it usually needs all three to define correct copy/ownership behavior. Rule of Five: in C++11 and later, such types should also consider move constructor and move assignment operator. Use Rule of Zero for most application types; use Rule of Three/Five when the type directly owns a resource or has nontrivial ownership/lifetime semantics.

struct Session {
    std::string user_id;
    std::vector<std::string> roles;
    std::unique_ptr<Connection> conn;

    // No custom destructor/copy/move operations.
};
Try answering this question with an AI coach

Error Handling

7Explain C++ exception handling, stack unwinding, destructor interaction, and service exception boundaries.

C++ exceptions transfer control from a `throw` expression to the nearest matching `catch`. During propagation, stack unwinding destroys fully constructed automatic objects in reverse order, so RAII cleanup runs automatically. Destructors should generally not throw; if an exception escapes a `noexcept` destructor or another exception escapes during active unwinding, the program calls `std::terminate`. Exceptions should usually be caught by reference, commonly `const&`, to avoid slicing and unnecessary copies. Backend services should define exception boundaries, such as request handlers, worker-thread entry points, RPC/HTTP framework callbacks, and `main`, where exceptions are logged, converted to error responses or status codes, and prevented from escaping into inappropriate contexts such as C APIs, destructors, threads, or `noexcept` functions.

struct Conn {
    ~Conn() noexcept { /* close or return connection to pool */ }
};

void handle() {
    Conn c;
    throw std::runtime_error("db failed");
} // c is destroyed while the exception propagates
Try answering this question with an AI coach

8What happens if a destructor throws, and how should backend types report cleanup failures?

Destructors are implicitly `noexcept(true)` in normal cases, so if an exception escapes such a destructor, `std::terminate` is called. Even if a destructor is explicitly declared `noexcept(false)`, throwing during stack unwinding is dangerous because a second escaping exception while another exception is active also terminates the program. Therefore destructors should perform best-effort cleanup and should not let exceptions escape. Backend types should report cleanup failures through explicit operations such as `close()`, `flush()`, `commit()`, `stop()`, or `shutdown()` that return an error/`expected` or throw before destruction. The destructor can log, emit metrics, suppress errors, or perform safe fallback cleanup, but should not be the primary error-reporting channel for actionable failures.

class FileWriter {
public:
    std::expected<void, Error> close() noexcept; // reports flush/close failure explicitly

    ~FileWriter() noexcept {
        if (!closed_) {
            auto r = close();
            if (!r) log_error(r.error()); // destructor does not throw
        }
    }
private:
    bool closed_ = false;
};
Try answering this question with an AI coach

Standard Library

9Why can an empty C++ vector object occupy memory even when its size and capacity are zero?

The vector object and its dynamically allocated element storage are different things. Even when size() and capacity() are both zero, the object must represent its state and support future operations. A common implementation stores begin, end, and end-of-storage pointers, possibly together with allocator or debugging state. Therefore sizeof(vector<T>) is nonzero even when no element buffer has been allocated. The standard does not require a specific number of pointers or a fixed byte size, so architecture, library, allocator type, and build mode can change it. Also, an empty vector can have nonzero capacity after reserve or clear, in which case it may retain an allocation as well. Distinguish the control object's footprint from live elements and reserved storage when measuring memory.

Try answering this question with an AI coach

10How do a stack and an ordinary queue differ, and which kind of task naturally fits each one?

A stack removes the most recently added item first: last in, first out. Its core operations are push, pop and peek at the top. This naturally fits nested work such as parsing balanced delimiters, depth-first traversal or undoing the latest action. An ordinary queue removes the oldest waiting item first: first in, first out, using enqueue at the rear and dequeue at the front. It fits breadth-first traversal or serving work in arrival order. Both can support constant-time end operations with suitable arrays, ring buffers or linked structures; implementation choice affects capacity and memory locality. A priority queue is different because removal follows priority rather than arrival order. Neither basic ordering rule alone guarantees thread safety, bounded memory or fair completion when processing times differ.

Try answering this question with an AI coach

11Compare std::map, std::unordered_map, and flat-map-style containers for backend lookup tables.

std::map is an ordered, usually tree-based associative container with logarithmic lookup/insert/erase; it is useful when sorted iteration, range queries, or ordering guarantees matter. std::unordered_map is hash-table based with average constant-time exact-key operations and no key ordering; it is often a good default for large mutable lookup tables when hashing is good. A flat-map-style container stores sorted key/value pairs contiguously, giving good cache locality and fast iteration/binary-search lookup, but insertion and erasure in the middle are linear. For backend lookup tables, choose based on whether the workload needs ordering/ranges, mostly exact lookups, frequent mutation, predictable latency, memory overhead, and cache behavior.

// Exact lookup, frequently updated:
std::unordered_map<std::string, User> users_by_id;

// Need sorted iteration or lower_bound/range queries:
std::map<std::string, User> users_by_id_ordered;

// Build once, query many times: vector sorted by key is a common flat-map style.
std::vector<std::pair<std::string, User>> users;
std::sort(users.begin(), users.end(), [](auto const& a, auto const& b) {
    return a.first < b.first;
});

auto it = std::lower_bound(users.begin(), users.end(), std::string_view{"u123"},
    [](auto const& p, std::string_view key) { return p.first < key; });
Try answering this question with an AI coach

12Explain std::optional and typical backend use cases for representing absent values.

std::optional<T> represents either a contained T value or no value. The empty state is represented by std::nullopt; code can check has_value() or use the optional in a boolean context, access the value with * or value(), and supply a default with value_or(). In backend code it is useful for nullable database fields, optional request/configuration fields, cache or repository misses where absence is expected, and domain states where a sentinel like -1 or an empty string would be ambiguous. It models absence of a value, not polymorphism or rich error information.

struct UserProfile {
    std::string id;
    std::optional<std::string> display_name; // absent if user has not set it
};

std::string label(UserProfile const& u) {
    return u.display_name.value_or("anonymous");
}
Try answering this question with an AI coach

13What are std::string_view and std::span, and what lifetime hazards do non-owning views introduce?

std::string_view is a non-owning view of a contiguous character sequence; std::span<T> is a non-owning view of a contiguous sequence of T. They are useful for zero-copy parameters and buffer APIs because they carry a pointer and a length without allocating or owning memory. The main hazard is lifetime: the referenced storage must outlive the view and must not be invalidated while the view is used. Returning or storing a view to a temporary, local object, destroyed object, or reallocated container can leave a dangling view.

std::string_view bad() {
    std::string s = "hello";
    return std::string_view{s}; // dangling after return
}

void ok(std::string_view name) {
    // safe only during this call if caller's data outlives the call
}
Try answering this question with an AI coach

Concurrency

14How do std::mutex, std::shared_mutex, and std::recursive_mutex differ, and when would you choose each?

std::mutex provides exclusive locking: only one thread can hold it, so it is the default choice for protecting shared mutable state. std::shared_mutex supports shared reader locks and exclusive writer locks: many readers may hold the lock concurrently, but writers need exclusive access. Choose it for read-mostly data when reader concurrency is worth the overhead and when writer fairness/starvation is acceptable or handled. std::recursive_mutex is an exclusive mutex that the same thread may lock multiple times and must unlock the same number of times; use it rarely, mainly for legacy or re-entrant code, because it can hide poor locking design.

std::mutex m;
std::shared_mutex sm;
std::recursive_mutex rm;

// Default exclusive protection
{
    std::lock_guard<std::mutex> lk(m);
    // modify shared state
}

// Read-mostly protection
{
    std::shared_lock<std::shared_mutex> read_lk(sm); // many readers allowed
    // read shared state
}
{
    std::unique_lock<std::shared_mutex> write_lk(sm); // exclusive writer
    // modify shared state
}

// Recursive locking by same thread, usually avoid if possible
void legacy_api() {
    std::lock_guard<std::recursive_mutex> lk(rm);
    // may call another function that also locks rm
}
Try answering this question with an AI coach

Language Features

15How does a C++ function object let a caller use function-call syntax while preserving configuration between calls?

A function object is a class instance with operator(), so callers can write object(arguments) as if calling a function. Its data members retain configuration or state between calls. For example, a Threshold predicate can store a limit and implement bool operator()(int value) const to compare each value with that limit. Unlike an ordinary function pointer, different instances can carry different limits while sharing the same class implementation. If calls update counters or other state, operator() may be non-const or use deliberately mutable state. Copying the function object normally copies its members, which may create independent state or shared state depending on their types. This matters when algorithms copy predicates and when several threads invoke the same object. Define ownership, constness, and synchronization according to the intended use.

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