Skip to main content
Computer Science & Languages

C++ Interview Questions

All Levels (Junior to Staff)16 Questions

C++ systems programming guide: RAII, pointer semantics, move semantics, memory alignment, virtual method tables (vtables), and modern C++20 features.

25 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice C++ Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

What is RAII (Resource Acquisition Is Initialization), and how does it provide exception safety?

Senior Engineering Answer

RAII ties the lifetime of a resource (heap memory, file descriptors, sockets, mutex locks) to the lifetime of a stack-allocated object. The resource is acquired in the constructor and released deterministically in the destructor. Because C++ guarantees stack unwinding invokes destructors for all constructed local objects when an exception is thrown or an early return occurs, RAII eliminates resource leaks without needing finally blocks.

Production Code Example
void writeLog(std::mutex& mtx, std::ofstream& out, std::string_view msg) {
    std::lock_guard<std::mutex> lock(mtx); // Unlocks automatically on scope exit
    out << msg << '\n';
}
Common Interview Trap / Anti-Pattern:

Throwing an exception from inside a destructor while another exception is already unwinding the stack: this immediately calls std::terminate() and crashes the process.

Question #2FundamentalJunior

What is the difference between a pointer and a reference in C++, and when should you use each?

Senior Engineering Answer

A reference (T&) is an alias to an existing object: it must be initialized at declaration, cannot be null in well-formed code, and cannot be reseated to refer to a different object. A pointer (T*) is a distinct variable holding a memory address: it can be null (nullptr), reassigned to point elsewhere, and supports pointer arithmetic. Prefer references (especially const T& or std::string_view) for non-optional parameters, and smart pointers or raw non-owning pointers when nullability or reseating is required.

Production Code Example
void increment(int& x) { ++x; }        // Non-null required
void tryIncrement(int* x) { if (x) ++(*x); } // Optional / nullable
Common Interview Trap / Anti-Pattern:

Returning a reference or pointer to a local stack variable: the stack frame is destroyed on return, producing a dangling reference and undefined behavior.

Question #3FundamentalJunior

Explain the Rule of Zero, Rule of Three, and Rule of Five in modern C++.

Senior Engineering Answer

The Rule of Three states that if a class manually manages a resource and defines any of destructor, copy constructor, or copy assignment operator, it likely needs all three. Since C++11, the Rule of Five adds the move constructor and move assignment operator to avoid expensive deep copies on temporaries. Best practice in modern C++ is the Rule of Zero: compose classes exclusively from RAII members (std::unique_ptr, std::vector, std::string) so the compiler-generated special member functions are automatically correct.

Production Code Example
struct ConnectionConfig {
    std::string host;
    std::vector<std::string> endpoints;
    // Rule of Zero: no custom destructor, copy, or move needed
};
Common Interview Trap / Anti-Pattern:

Declaring a custom destructor (even = default) suppresses implicit generation of the move constructor and move assignment operator, silently falling back to slow copies.

Question #4FundamentalJunior

Why should base classes with virtual functions always have a virtual destructor?

Senior Engineering Answer

When a derived object is deleted through a base-class pointer (delete basePtr; or std::unique_ptr<Base> going out of scope), a non-virtual base destructor causes static dispatch to run only ~Base(), skipping ~Derived() and invoking undefined behavior (and leaking derived resources). Declaring virtual ~Base() = default ensures dynamic dispatch invokes ~Derived() first and then ~Base(). (Alternatively, non-polymorphic bases can declare a protected non-virtual destructor to prevent deletion via Base*.)

Production Code Example
class Stream {
public:
    virtual ~Stream() = default;
    virtual size_t read(std::byte* buf, size_t len) = 0;
};
Common Interview Trap / Anti-Pattern:

Calling virtual functions inside a constructor or destructor expecting derived overrides to run: during Base's constructor/destructor, the dynamic type of *this is Base, so virtual dispatch resolves to Base's implementation.

Question #5IntermediateMid-Level

Compare std::unique_ptr, std::shared_ptr, and std::weak_ptr, including control block overhead.

Senior Engineering Answer

std::unique_ptr enforces exclusive ownership with zero memory or CPU overhead over a raw pointer (unless using a stateful custom deleter). std::shared_ptr shares ownership via a heap-allocated control block holding an atomic strong refcount, an atomic weak refcount, and the deleter; prefer std::make_shared<T>() so the object and control block are allocated in a single heap allocation. std::weak_ptr observes a shared_ptr without incrementing the strong count, breaking reference cycles and requiring .lock() to safely obtain a temporary shared_ptr.

Production Code Example
auto sp = std::make_shared<int>(42); // Single allocation for int + control block
std::weak_ptr<int> wp = sp;
if (auto locked = wp.lock()) {
    // Safe atomic promotion while object is alive
}
Common Interview Trap / Anti-Pattern:

Constructing two separate std::shared_ptr instances from the same raw pointer (shared_ptr<T>(raw); shared_ptr<T>(raw)): this creates two independent control blocks and causes a double-free crash.

Question #6IntermediateMid-Level

Explain lvalues, rvalues, move semantics, and std::move vs std::forward.

Senior Engineering Answer

An lvalue has an identifiable memory location (e.g., named variables), whereas an rvalue (prvalue/xvalue) is a temporary or expiring value whose internal buffers can be stolen. std::move does not move anything at runtime; it is an unconditional static_cast to an rvalue reference (T&&) enabling move constructors to pilfer pointers/handles and leave the source valid-but-unspecified. std::forward<T> is a conditional cast used with forwarding references (T&& in deduced template contexts) to preserve the original lvalue/rvalue category (perfect forwarding).

Production Code Example
template <typename T, typename... Args>
std::unique_ptr<T> make_custom(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Common Interview Trap / Anti-Pattern:

Using std::move on a local variable in a return statement (return std::move(localVec);): this disables guaranteed/Named Return Value Optimization (NRVO) and forces a move instead of constructing directly in the caller's slot.

Question #7IntermediateMid-Level

How do std::string_view and std::span eliminate unnecessary copies, and what dangling hazards do they introduce?

Senior Engineering Answer

std::string_view (C++17) and std::span<T> (C++20) are lightweight non-owning views (pointer + length) over contiguous character or object sequences. Accepting std::string_view lets a function accept string literals, std::string, and substrings without allocating heap memory. Because they do not own the underlying storage, returning a string_view into a temporary std::string or storing one past the owner's lifetime leaves a dangling pointer.

Production Code Example
std::string_view firstWord(std::string_view s) {
    auto pos = s.find(' ');
    return pos == std::string_view::npos ? s : s.substr(0, pos);
}
// Danger: std::string_view sv = getTempString(); // Dangling immediately!
Common Interview Trap / Anti-Pattern:

Passing string_view::data() directly to a C API expecting a null-terminated char*: substrings created via .substr() or .remove_suffix() are NOT null-terminated!

Question #8IntermediateMid-Level

What happens to iterators and references when std::vector grows, and how does emplace_back differ from push_back?

Senior Engineering Answer

std::vector stores elements in a single contiguous heap buffer. When push_back/emplace_back exceeds capacity(), vector allocates a new buffer (typically 1.5x or 2x), moves (if noexcept move constructor exists, otherwise copies!) all elements over, and frees the old buffer—invalidating all pointers, references, and iterators into the vector. emplace_back constructs the element in place directly inside the vector's buffer using forwarded constructor arguments, avoiding temporary object creation when constructing from arguments.

Production Code Example
class Buffer {
public:
    Buffer(Buffer&&) noexcept; // noexcept lets std::vector move instead of copy on resize!
};
Common Interview Trap / Anti-Pattern:

Forgetting noexcept on a custom move constructor: for strong exception safety, std::vector::push_back falls back to copying every element during reallocation unless the move constructor is marked noexcept.

Question #9AdvancedSenior

How do virtual tables (vtables) and vptrs implement dynamic dispatch, and what are their performance costs?

Senior Engineering Answer

For any class with at least one virtual function, the compiler generates a static vtable (an array of function pointers for that class's virtual overrides and RTTI pointer) and embeds a hidden vptr (usually the first 8 bytes of each object instance) pointing to its class's vtable. Calling a virtual method loads the vptr, indexes into the vtable, and performs an indirect call. Beyond the 8-byte per-object memory cost, indirect calls hinder function inlining and can suffer CPU branch-target misprediction when iterating over heterogeneous objects—though compilers can devirtualize calls marked final or proven statically.

Production Code Example
struct Base { virtual int eval() const = 0; };
struct Fast final : Base { int eval() const override { return 7; } };
// `final` lets the compiler devirtualize and inline Fast::eval() calls
Common Interview Trap / Anti-Pattern:

Calling memset or memcpy on polymorphic or non-trivially-copyable C++ objects: memset overwrites the hidden vptr with zeros, crashing on the next virtual call.

Question #10AdvancedSenior

Why does Undefined Behavior (UB) matter so much in C++, and what common UB bugs break under -O2/-O3?

Senior Engineering Answer

In C++, Undefined Behavior imposes zero requirements on the compiler—it is not merely 'unpredictable output,' because optimizing compilers actively assume UB never happens and delete branches or reorder code based on that assumption. Common sources include signed integer overflow (while unsigned wraps modulo 2^N), out-of-bounds array access, dereferencing null/dangling pointers, data races, and violating strict aliasing rules (accessing an object through an unrelated pointer type other than char*/std::byte*). Enable -fsanitize=address,undefined (ASan/UBSan) in CI to catch UB early.

Production Code Example
// UB: signed overflow lets the compiler optimize `if (x + 1 < x)` to `false`
bool willOverflow(int x) {
    return x > std::numeric_limits<int>::max() - 1; // Check BEFORE adding
}
Common Interview Trap / Anti-Pattern:

Casting a uint8_t* buffer directly to uint32_t* to parse network bytes: this violates strict aliasing and alignment rules—use std::memcpy into a uint32_t (which modern compilers optimize to a single mov instruction) or std::bit_cast in C++20.

Question #11AdvancedSenior

How do C++20 Concepts replace SFINAE for template constraints, and how does subsumption resolve overloads?

Senior Engineering Answer

Before C++20, constraining templates relied on SFINAE (std::enable_if) or tag dispatch, producing unreadable error walls. C++20 Concepts define named compile-time boolean predicates over types using requires expressions, giving clear diagnostics when constraints fail. Concepts also support subsumption: if overload B's constraint logically implies overload A's constraint (e.g., RandomAccessIterator refines BidirectionalIterator), the compiler selects the more constrained overload without ambiguity.

Production Code Example
template <typename T>
concept Hashable = requires(T a) {
    { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};

template <Hashable T>
void insertKey(const T& key) { /* ... */ }
Common Interview Trap / Anti-Pattern:

Thinking Concepts perform runtime type checks or allow dynamic polymorphism: Concepts are purely compile-time constraints evaluated during template instantiation.

Question #12AdvancedSenior

Compare std::variant + std::visit vs virtual inheritance, and constexpr/consteval compile-time evaluation.

Senior Engineering Answer

std::variant is a type-safe tagged union storing one of a closed set of alternatives inline (no heap allocation, cache-local), paired with std::visit for exhaustive compile-time checked dispatch—ideal when the set of types is fixed and operations vary. Virtual inheritance excels when the set of types is open for extension. Meanwhile, constexpr functions can run at either compile time or runtime, whereas C++20 consteval functions are immediate functions guaranteed to evaluate strictly at compile time (producing compile errors if given runtime inputs).

Production Code Example
consteval uint32_t fnv1a(std::string_view s) {
    uint32_t h = 2166136261u;
    for (unsigned char c : s) h = (h ^ c) * 16777619u;
    return h;
}
constexpr uint32_t tag = fnv1a("OrderCreated"); // Zero runtime cost
Common Interview Trap / Anti-Pattern:

Assuming constexpr guarantees compile-time evaluation when called in a non-constexpr context: only constexpr/constinit variables or consteval functions force compile-time evaluation.

Question #13StaffPrincipal / Staff

Explain C++ memory ordering (memory_order_relaxed, acquire/release, seq_cst) in lock-free programming.

Senior Engineering Answer

C++ std::atomic defaults to memory_order_seq_cst, guaranteeing a single total modification order visible to all threads (emitting full fences on weakly ordered architectures like ARM64). memory_order_relaxed guarantees atomicity and modification order of that single variable only, with zero cross-variable ordering guarantees (ideal for independent metrics counters). Acquire-release semantics synchronize threads cheaply: a store(release) on thread A paired with a load(acquire) on thread B observing that value guarantees all memory writes before the release are visible after the acquire (the foundation of lock-free SPSC ring buffers).

Production Code Example
std::atomic<bool> ready{false};
int payload = 0;

// Producer: payload = 42; ready.store(true, std::memory_order_release);
// Consumer: while (!ready.load(std::memory_order_acquire)) {} assert(payload == 42);
Common Interview Trap / Anti-Pattern:

Testing lock-free code only on x86_64: x86 has a strong TSO memory model that hides missing acquire/release barriers, causing silent corruption when deployed on ARM64 (Graviton/Apple Silicon) servers.

Question #14StaffPrincipal / Staff

How do C++20 Coroutines (co_await, co_yield, co_return) work at the ABI and frame-allocation level?

Senior Engineering Answer

C++20 coroutines are stackless: when a function uses co_await, co_yield, or co_return, the compiler transforms it into a coroutine frame storing parameters, local variables, suspension state, and a promise_type object. Calling the coroutine allocates the frame (on the heap by default, though HALO—Heap Allocation Elision Optimization—can place it on the caller's stack if its lifetime is bounded), initializes the promise, and returns a handle/task wrapper. Execution suspends at co_await points by returning control to the caller/scheduler and resumes later via std::coroutine_handle::resume().

Production Code Example
// Coroutines suspend without blocking OS threads; awaiter controls scheduling
Task<int> fetchPrice(HttpClient& c) {
    auto resp = co_await c.getAsync("/price");
    co_return parseInt(resp.body);
}
Common Interview Trap / Anti-Pattern:

Capturing references to temporary arguments passed into a coroutine (e.g., std::string_view or const T& to a temporary): if the coroutine suspends at initial_suspend or co_await, the caller's temporary is destroyed before the coroutine reads it.

Question #15StaffPrincipal / Staff

How do CPU cache lines, false sharing, and Structure-of-Arrays (SoA) vs Array-of-Structures (AoS) impact C++ latency?

Senior Engineering Answer

Modern CPUs fetch memory in 64-byte cache lines and prefetch sequential accesses. An Array-of-Structures (std::vector<Particle>) wastes cache bandwidth if a hot loop only reads one field (e.g., position.x) while pulling unused fields (color, name) into L1 cache. Switching to Structure-of-Arrays (SoA) keeps hot fields contiguous for SIMD vectorization. Across threads, separate atomic variables residing within the same 64-byte cache line suffer false sharing; align concurrent per-thread slots with alignas(std::hardware_destructive_interference_size) (typically 64 bytes).

Production Code Example
struct alignas(64) WorkerSlot {
    std::atomic<uint64_t> processed{0};
};
Common Interview Trap / Anti-Pattern:

Reaching for std::list or std::map on hot paths: pointer-chasing across scattered heap nodes causes L1/L2 cache misses on every step, whereas flat contiguous containers (std::vector, flat_hash_map) routinely beat pointer-based structures by 10x+.

Question #16StaffPrincipal / Staff

How do exceptions, RTTI, and custom allocators (std::pmr) impact zero-allocation and real-time C++ systems?

Senior Engineering Answer

C++ uses table-based ('zero-cost') exception handling: the happy path has minimal instruction overhead (except inhibiting some compiler optimizations), while throwing unwinds tables dynamically and allocates exception objects—unacceptable for hard real-time or kernel/embedded systems, which often compile with -fno-exceptions -fno-rtti and return std::expected<T, E> (C++23). For allocation control, std::pmr::memory_resource (e.g., monotonic_buffer_resource backed by a stack buffer) lets standard containers (std::pmr::vector, std::pmr::string) perform zero-syscall arena allocations per request.

Production Code Example
#include <memory_resource>
std::array<std::byte, 4096> stackBuf;
std::pmr::monotonic_buffer_resource arena(stackBuf.data(), stackBuf.size());
std::pmr::vector<std::pmr::string> tokens(&arena);
Common Interview Trap / Anti-Pattern:

Using std::pmr::monotonic_buffer_resource without an upstream null_memory_resource() or bounded growth check in long-lived loops: once the stack buffer fills, it silently falls back to heap allocations via the default upstream new_delete_resource().

C++ Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This C++ preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Computer Science & Languages.

JuniorFundamental

What is RAII (Resource Acquisition Is Initialization), and how does it provide exception safety?

JuniorFundamental

What is the difference between a pointer and a reference in C++, and when should you use each?

JuniorFundamental

Explain the Rule of Zero, Rule of Three, and Rule of Five in modern C++.

JuniorFundamental

Why should base classes with virtual functions always have a virtual destructor?

Mid-LevelIntermediate

Compare std::unique_ptr, std::shared_ptr, and std::weak_ptr, including control block overhead.

Mid-LevelIntermediate

Explain lvalues, rvalues, move semantics, and std::move vs std::forward.

Frequently Asked Technical Interview Questions (C++)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is RAII and why is it central to modern C++ resource safety?
RAII binds resource ownership (heap memory, locks, file handles) to stack-object lifetimes: constructors acquire resources and destructors release them. Because stack unwinding always runs destructors on scope exit or exceptions, RAII guarantees leak-free cleanup.
What is the Rule of Five vs the Rule of Zero?
The Rule of Five states that a class manually managing a raw resource should explicitly define or delete its destructor, copy constructor, copy assignment, move constructor, and move assignment. The Rule of Zero avoids manual resource code altogether by composing RAII types like std::unique_ptr and std::vector.
How do std::unique_ptr, std::shared_ptr, and std::weak_ptr differ?
std::unique_ptr enforces exclusive ownership with zero overhead over a raw pointer. std::shared_ptr enables shared ownership using an atomic reference-counted control block. std::weak_ptr holds a non-owning observer handle that breaks cyclic references and promotes safely via lock().
How does std::move differ from std::forward?
std::move unconditionally casts an expression to an rvalue reference so move constructors can transfer internal resources without copying. std::forward conditionally preserves the original lvalue or rvalue value category of a deduced forwarding-reference parameter.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks