C++ Interview Questions
C++ systems programming guide: RAII, pointer semantics, move semantics, memory alignment, virtual method tables (vtables), and modern C++20 features.
Practice C++ Interview Questions
Showing 16 of 16 technical questions with engineering explanations
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.
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';
}Throwing an exception from inside a destructor while another exception is already unwinding the stack: this immediately calls std::terminate() and crashes the process.
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.
void increment(int& x) { ++x; } // Non-null required
void tryIncrement(int* x) { if (x) ++(*x); } // Optional / nullableReturning a reference or pointer to a local stack variable: the stack frame is destroyed on return, producing a dangling reference and undefined behavior.
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.
struct ConnectionConfig {
std::string host;
std::vector<std::string> endpoints;
// Rule of Zero: no custom destructor, copy, or move needed
};Declaring a custom destructor (even = default) suppresses implicit generation of the move constructor and move assignment operator, silently falling back to slow copies.
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*.)
class Stream {
public:
virtual ~Stream() = default;
virtual size_t read(std::byte* buf, size_t len) = 0;
};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.
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.
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
}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.
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).
template <typename T, typename... Args>
std::unique_ptr<T> make_custom(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}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.
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.
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!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!
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.
class Buffer {
public:
Buffer(Buffer&&) noexcept; // noexcept lets std::vector move instead of copy on resize!
};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.
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.
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() callsCalling memset or memcpy on polymorphic or non-trivially-copyable C++ objects: memset overwrites the hidden vptr with zeros, crashing on the next virtual call.
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.
// 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
}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.
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.
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) { /* ... */ }Thinking Concepts perform runtime type checks or allow dynamic polymorphism: Concepts are purely compile-time constraints evaluated during template instantiation.
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).
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 costAssuming constexpr guarantees compile-time evaluation when called in a non-constexpr context: only constexpr/constinit variables or consteval functions force compile-time evaluation.
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).
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);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.
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().
// 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);
}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.
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).
struct alignas(64) WorkerSlot {
std::atomic<uint64_t> processed{0};
};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+.
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.
#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);
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 examplesThis 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.
What is RAII (Resource Acquisition Is Initialization), and how does it provide exception safety?
What is the difference between a pointer and a reference in C++, and when should you use each?
Explain the Rule of Zero, Rule of Three, and Rule of Five in modern C++.
Why should base classes with virtual functions always have a virtual destructor?
Compare std::unique_ptr, std::shared_ptr, and std::weak_ptr, including control block overhead.
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?
What is the Rule of Five vs the Rule of Zero?
How do std::unique_ptr, std::shared_ptr, and std::weak_ptr differ?
How does std::move differ from std::forward?
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.