22 C++ Interview Questions: RAII, Move Semantics, UB & C++26
22 cpp interview questions with tested sample answers: RAII, smart pointers, move semantics, vtables, undefined behavior, atomics, C++23 and C++26.
Last updated: November 2026
Quick Answer
C++ interviewers test whether you understand what the language does with memory and time: who owns each object and when its destructor runs (RAII), when a value is copied versus moved, how virtual dispatch works, which code is undefined behavior, and what the standard library guarantees about iterators and threads. Then they ask you to build something small, such as a smart pointer or an LRU cache, and explain every allocation. Rehearse the spoken answers in OphyAI Interview Practice, and use OphyAI Coding Copilot for the live coding round. Every complete code sample on this page of cpp interview questions was compiled with g++ 13.3 (-std=c++23 -Wall -Wextra, plus AddressSanitizer and UndefinedBehaviorSanitizer) and run; the printed output is shown under each block.
| # | Question | What it tests |
|---|---|---|
| 1 | What is RAII? | Deterministic cleanup |
| 2 | unique_ptr vs shared_ptr vs weak_ptr | Ownership |
| 3 | make_shared vs new | Allocation and exception safety |
| 4 | Move semantics and noexcept moves | Value categories |
| 5 | Rule of zero, three and five | Special member functions |
| 6 | How virtual functions and vtables work | Dynamic dispatch |
| 7 | Object slicing | Value vs reference semantics |
| 8 | What undefined behavior is | The abstract machine |
| 9 | Templates vs concepts | Generic programming |
| 10 | const, constexpr, consteval, constinit | Compile-time evaluation |
The Questions, With Sample Answers
Questions 1-10 are the core, 11-20 cover the library, concurrency and new standards, and 21-22 are live coding tasks.
1. “What is RAII, and why does C++ rely on it?”
Why they ask. RAII (Resource Acquisition Is Initialization) is the idea modern C++ is built on.
Sample answer. “RAII ties a resource’s lifetime to an object’s lifetime. The constructor acquires the resource, a file, a lock, a socket or heap memory, and the destructor releases it. Because C++ runs destructors deterministically when an object goes out of scope, including during stack unwinding after an exception, cleanup happens on every path without a finally block. That is why std::lock_guard, std::unique_ptr, std::vector and std::fstream all look the same: they own something and give it back in the destructor. The C++ Core Guidelines make it rule R.1.”
#include <cstdio>
#include <stdexcept>
class File {
public:
explicit File(const char* path) : f_(std::fopen(path, "w")) {
if (!f_) throw std::runtime_error("open failed");
}
~File() { std::fclose(f_); std::puts("closed"); }
File(const File&) = delete;
File& operator=(const File&) = delete;
void write(const char* s) { std::fputs(s, f_); }
private:
std::FILE* f_;
};
int main() {
try {
File f("/tmp/raii_demo.txt");
f.write("hello\n");
throw std::runtime_error("boom");
} catch (const std::exception& e) {
std::puts(e.what());
}
}
Output: closed, then boom. The destructor runs before the catch block does.
Weak answers. “It means you call delete in the destructor”, with no mention of exceptions, scope exit or non-memory resources.
2. “When do you use unique_ptr, shared_ptr and weak_ptr?”
Why they ask. Ownership is the most common C++ design question, and shared_ptr everywhere is a warning sign.
Sample answer. “unique_ptr is my default: one owner, no reference count, typically the same size as a raw pointer with the default deleter, and it can only be moved, not copied. shared_ptr is for genuinely shared ownership, where no single object outlives the others; it keeps an atomic reference count in a control block, so copies cost more. weak_ptr observes a shared_ptr without keeping it alive, and I call lock() to get a temporary shared_ptr if the object still exists. The classic use is breaking cycles: if a parent and child hold shared_ptrs to each other, neither count reaches zero and both leak. Raw pointers and references are still fine for non-owning access.”
#include <iostream>
#include <memory>
struct Node {
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // weak: breaks the cycle
~Node() { std::cout << "~Node\n"; }
};
int main() {
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b;
b->prev = a;
std::cout << a.use_count() << ' ' << b.use_count() << '\n';
if (auto p = b->prev.lock()) std::cout << "prev alive\n";
std::unique_ptr<int> u = std::make_unique<int>(42);
std::unique_ptr<int> v = std::move(u); // ownership moves, u is now null
std::cout << (u == nullptr) << ' ' << *v << '\n';
}
Output: 1 2, prev alive, 1 42, then ~Node twice.
Weak answers. “shared_ptr is safer, so I use it everywhere”, or not knowing that a cycle of shared_ptrs leaks.
3. “Why prefer make_shared and make_unique over new?”
Why they ask. It checks whether you know what a shared_ptr allocates.
Sample answer. “make_shared does one allocation that holds both the object and the control block, where shared_ptr<T>(new T) does two, so it is faster and has better locality. Both factory functions also mean I never write a bare new, which is Core Guidelines R.11, and they keep the code exception-safe: the object is owned by a smart pointer the moment it exists. One trade-off with make_shared is that the object’s memory is not released until the last weak_ptr is gone too, because the object and the control block share an allocation. For a large object with long-lived weak references, I might construct the shared_ptr separately.”
Weak answers. “They are just shorter to type”, with no mention of the single allocation.
Practice explaining questions 1-3 aloud in Interview Practice; the follow-up questions push on exactly where the destructor runs.
4. “What are move semantics, and why does noexcept on a move constructor matter?”
Why they ask. The noexcept detail shows whether you know how std::vector grows.
Sample answer. “An lvalue has a name and an identity; an rvalue is a temporary or something I have explicitly given up with std::move. A move constructor takes an rvalue reference and steals its resources, a pointer swap instead of a deep copy, leaving the source valid but unspecified. std::move itself moves nothing: it is a cast to an rvalue reference that makes the move overload eligible. The noexcept part matters because when vector reallocates, it wants the strong exception guarantee. If the move constructor might throw, a failure halfway through would leave elements in neither buffer, so the library copies instead. Marking moves noexcept, which is Core Guidelines C.66, lets vector move.”
#include <iostream>
#include <vector>
struct Loud {
Loud() = default;
Loud(const Loud&) { std::cout << "copy "; }
Loud(Loud&&) noexcept { std::cout << "move "; }
};
struct Risky {
Risky() = default;
Risky(const Risky&) { std::cout << "copy "; }
Risky(Risky&&) { std::cout << "move "; } // not noexcept
};
int main() {
std::vector<Loud> a; a.reserve(1);
a.emplace_back(); a.emplace_back(); // growth: existing element is moved
std::cout << '\n';
std::vector<Risky> b; b.reserve(1);
b.emplace_back(); b.emplace_back(); // growth: existing element is copied
std::cout << '\n';
}
Output: move, then copy. Only Loud’s move is noexcept.
Weak answers. “std::move moves the object”, or never having heard why vector falls back to copying.
5. “What are the rule of zero, the rule of three and the rule of five?”
Why they ask. Wrong special member functions cause double frees and leaks.
Sample answer. “The five special operations are the destructor, copy constructor, copy assignment, move constructor and move assignment. The rule of three, from C++98, says if you need to write one of destructor, copy constructor or copy assignment, you probably need all three, because you are managing a resource. C++11 added the two moves, so it became the rule of five, and the Core Guidelines phrase it as C.21: if you define or delete any of them, define or delete them all. The rule of zero, C.20, is the one I actually aim for: compose classes from members that already manage themselves, such as std::string, std::vector and unique_ptr, and write none of the five. Only a class whose job is ownership should implement them.”
#include <cstring>
#include <iostream>
#include <string>
#include <utility>
// Rule of five: this class owns a raw buffer, so it defines all five.
class Buffer {
public:
explicit Buffer(std::size_t n) : size_(n), data_(new char[n]{}) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer& o) : size_(o.size_), data_(new char[o.size_]) {
std::memcpy(data_, o.data_, size_);
}
Buffer& operator=(const Buffer& o) { // copy-and-swap: strong guarantee
Buffer tmp(o);
swap(tmp);
return *this;
}
Buffer(Buffer&& o) noexcept
: size_(std::exchange(o.size_, 0)), data_(std::exchange(o.data_, nullptr)) {}
Buffer& operator=(Buffer&& o) noexcept {
Buffer tmp(std::move(o));
swap(tmp);
return *this;
}
void swap(Buffer& o) noexcept { std::swap(size_, o.size_); std::swap(data_, o.data_); }
std::size_t size() const { return size_; }
private:
std::size_t size_;
char* data_;
};
// Rule of zero: members manage themselves, so define none of the five.
struct Person {
std::string name;
Buffer avatar{16};
};
int main() {
Buffer a(8);
Buffer b = a; // copy
Buffer c = std::move(a); // move: a is left empty
std::cout << a.size() << ' ' << b.size() << ' ' << c.size() << '\n';
Person p{"Ada"};
Person q = p;
std::cout << q.name << ' ' << q.avatar.size() << '\n';
}
Output: 0 8 8, then Ada 16. Person copies correctly with zero special members.
Weak answers. Listing the functions without saying why declaring a destructor suppresses the implicit move operations, or forgetting self-assignment and exception safety in the copy assignment.
6. “How do virtual functions work? What is a vtable?”
Why they ask. It tests the cost of dynamic dispatch and the virtual destructor rule.
Sample answer. “The standard does not mention vtables, but every mainstream compiler implements virtual functions the same way. Each polymorphic class gets a static table of function pointers, and each object carries a hidden pointer to its class’s table. A virtual call loads that pointer, indexes the table and calls indirectly, which costs an extra load and usually blocks inlining, unless the compiler can devirtualize, for example with a final class. Two rules follow. A base class meant for deletion through a base pointer needs a virtual destructor, or deleting a derived object through it is undefined behavior; that is Core Guidelines C.35. And a virtual call inside a constructor dispatches to the class being constructed, not the derived override, because the derived part does not exist yet.”
#include <iostream>
#include <memory>
struct Shape {
Shape() { hello(); } // virtual call in a constructor
virtual ~Shape() { std::cout << "~Shape\n"; }
virtual double area() const = 0;
virtual void hello() const { std::cout << "Shape::hello\n"; }
};
struct Square : Shape {
explicit Square(double s) : s_(s) {}
~Square() override { std::cout << "~Square\n"; }
double area() const override { return s_ * s_; }
void hello() const override { std::cout << "Square::hello\n"; }
double s_;
};
int main() {
std::unique_ptr<Shape> p = std::make_unique<Square>(3.0);
std::cout << p->area() << '\n';
}
Output: Shape::hello, 9, ~Square, ~Shape.
Weak answers. “Virtual functions are slow, so avoid them”, with no idea of what the cost is, or forgetting the virtual destructor.
7. “What is object slicing?”
Why they ask. C++ objects are values unless you say otherwise.
Sample answer. “Slicing happens when a derived object is copied into a base-class object by value. Only the base subobject is copied, the derived members are dropped, and the copy’s dynamic type is the base, so virtual calls go to the base version. The fix is to pass by reference or pointer, and to store std::unique_ptr<Base> in containers. For a class hierarchy, I also consider deleting the base copy operations, or making them protected, so accidental slicing does not compile.”
#include <iostream>
#include <string>
struct Animal {
virtual ~Animal() = default;
virtual std::string speak() const { return "..."; }
};
struct Dog : Animal {
std::string speak() const override { return "woof"; }
};
void byValue(Animal a) { std::cout << a.speak() << '\n'; }
void byRef(const Animal& a) { std::cout << a.speak() << '\n'; }
int main() {
Dog d;
byValue(d); // sliced: only the Animal part is copied
byRef(d);
}
Output: ..., then woof. The by-value copy lost the Dog part.
Weak answers. Calling slicing memory corruption. Data is silently lost, not corrupted.
8. “What is undefined behavior? Give examples.”
Why they ask. UB is what breaks code under an optimizing compiler. Expect a follow-up on how you find it.
Sample answer. “Undefined behavior means the standard places no requirements on what happens, and the optimizer is allowed to assume it never occurs. Common examples are signed integer overflow, reading out of bounds, dereferencing a null or dangling pointer, using an object after its lifetime ends, a data race on a non-atomic variable, and breaking strict aliasing. Because the compiler assumes UB cannot happen, it can delete a later null check or turn an overflow check into true, so the bug shows up far from its cause, often only at -O2. I catch it with sanitizers, ASan and UBSan in CI, plus warnings and static analysis. C++26 also changes reading an uninitialized local variable from UB to erroneous behavior, a defined but wrong result that tools are encouraged to diagnose.”
#include <climits>
#include <iostream>
int next(int x) { return x + 1; } // UB if x == INT_MAX
int main() {
int big = INT_MAX;
std::cout << next(big) << '\n';
}
Built with -fsanitize=undefined, UBSan reports runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int' before the program prints -2147483648. Without the sanitizer, nothing warns you.
Weak answers. “UB means the program crashes.” Usually it does not, which is the problem.
9. “How do templates work, and what do C++20 concepts add?”
Why they ask. Generic code is everywhere, and concepts are widely adopted C++20.
Sample answer. “A template is a recipe the compiler instantiates for each set of arguments it is used with, so std::vector<int> and std::vector<double> are separate types with separate code. That gives zero-overhead generic code at the cost of compile time and binary size. Before C++20, constraints were expressed with SFINAE and enable_if, which worked but produced unreadable errors deep inside the template. A concept is a named compile-time predicate on types, and a requires clause or a constrained parameter like std::integral auto checks it at the call site. The error then says which constraint failed. Concepts also take part in overload resolution, so a more constrained overload wins, which replaces most tag-dispatch tricks.”
#include <concepts>
#include <iostream>
#include <string>
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template <Numeric T>
T sum_sq(T a, T b) { return a * a + b * b; }
// Abbreviated syntax with a constrained auto parameter
auto twice(std::integral auto x) { return x * 2; }
int main() {
std::cout << sum_sq(3, 4) << ' ' << sum_sq(1.5, 2.0) << ' ' << twice(21) << '\n';
// sum_sq(std::string("a"), std::string("b")); // error: constraints not satisfied
}
Output: 25 6.25 42. Uncommenting the std::string call fails at the call site with “constraints not satisfied”.
Weak answers. Saying concepts are “like interfaces” with run-time dispatch. They are checked entirely at compile time.
10. “What is the difference between const, constexpr, consteval and constinit?”
Why they ask. The four keywords look alike, so guessing shows quickly.
Sample answer. “const means read-only through this name; the value can still be computed at run time. constexpr on a variable means its value is a compile-time constant; on a function it means the function can be evaluated at compile time when its arguments are constants, and it can still run at run time otherwise. consteval, from C++20, makes an immediate function: every call must produce a compile-time constant, or the code does not compile. constinit, also C++20, applies to static and thread-local variables and guarantees they are initialized at compile time, which avoids the static initialization order problem, but the variable stays mutable. So: const is about mutation, constexpr is about can, consteval is about must, and constinit is about when initialization happens.”
#include <iostream>
constexpr int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
consteval int square(int n) { return n * n; } // must run at compile time
constinit int counter = fib(10); // static init, still mutable
int main(int argc, char**) {
constexpr int a = fib(20); // compile time
int b = fib(argc + 5); // same function at run time
static_assert(square(12) == 144);
// int c = square(argc); // error: argc is not a constant
const int d = argc; // const: read-only, but known only at run time
++counter;
std::cout << a << ' ' << b << ' ' << d << ' ' << counter << '\n';
}
Output with no command-line arguments: 6765 8 1 56.
Weak answers. “constexpr means the function always runs at compile time.” That is consteval.
Run a timed mock on questions 4-10 in Interview Practice and check the transcript for answers that drift past two minutes.
11. “Which STL container would you choose, and why?”
Why they ask. Container choice is a performance question about cache behavior, not only Big O.
Sample answer. “std::vector is my default because contiguous memory is cache-friendly; even inserting into the middle of a modest vector often beats a linked list in practice. std::deque gives cheap insertion at both ends. std::list is worth it only when I need stable iterators and constant-time splicing, as in an LRU cache. std::map is a balanced tree, ordered, with logarithmic operations; std::unordered_map is a hash table with average constant time but no ordering and poor locality, because nodes are allocated separately.”
| Container | Lookup | Insert | Notes |
|---|---|---|---|
vector | O(1) by index | Amortized O(1) at end | Contiguous; default choice |
deque | O(1) by index | O(1) at both ends | Not contiguous |
list | O(n) | O(1) with an iterator | Stable iterators, splice |
map / set | O(log n) | O(log n) | Ordered, balanced tree |
unordered_map | O(1) average | O(1) average | Rehash invalidates iterators |
Weak answers. Choosing list for “fast insertion” without mentioning the cost of finding the position, or ignoring memory layout entirely.
12. “When are iterators invalidated? Fix this erase loop.”
Why they ask. Erasing while iterating is a classic bug, and the rules differ per container.
Sample answer. “For vector, the standard says that if an insertion pushes the size past the capacity, the vector reallocates and every iterator, pointer and reference is invalidated. Without reallocation, those before the insertion point stay valid and those at or after it do not. erase invalidates iterators at or after the erased element. For unordered_map, a rehash invalidates iterators but not pointers or references to elements. Node-based containers such as map and list only invalidate iterators to the erased element. The loop bug is calling erase(it) and then ++it on a dead iterator. The fix is to use the iterator erase returns, or in C++20 just call std::erase_if.”
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6};
// Wrong: for (auto it = v.begin(); it != v.end(); ++it) if (*it % 2 == 0) v.erase(it);
for (auto it = v.begin(); it != v.end();) {
if (*it % 2 == 0) it = v.erase(it); // erase returns the next valid iterator
else ++it;
}
std::vector<int> w{1, 2, 3, 4, 5, 6};
std::erase_if(w, [](int x) { return x % 2 == 0; }); // C++20
for (int x : v) std::cout << x << ' ';
std::cout << "| ";
for (int x : w) std::cout << x << ' ';
std::cout << '\n';
}
Output: 1 3 5 | 1 3 5.
Weak answers. “Iterators are like pointers, so they stay valid.” Holding a reference to v[0] across a push_back is the same bug.
13. “Explain the C++ memory model. When would you use memory_order_acquire and release?”
Why they ask. Low-latency and GPU teams write lock-free code, and this is where bluffing shows.
Sample answer. “The standard defines a data race as two conflicting accesses from different threads, at least one non-atomic, with no happens-before relation between them, and a data race is undefined behavior. Atomics and mutexes are how you create happens-before. The default memory_order_seq_cst gives one global order for all sequentially consistent operations, which is easiest to reason about. release on a store and acquire on a load that reads that store form a pair: everything the writer did before the release is visible to the reader after the acquire, which is how I publish data with a flag. relaxed only guarantees atomicity, which is fine for a statistics counter where no other data depends on the value.”
#include <atomic>
#include <cassert>
#include <iostream>
#include <thread>
#include <vector>
int payload = 0; // plain data, published via the flag
std::atomic<bool> ready{false};
std::atomic<int> hits{0};
int main() {
std::thread producer([] {
payload = 42;
ready.store(true, std::memory_order_release); // publishes payload
});
std::thread consumer([] {
while (!ready.load(std::memory_order_acquire)) {} // pairs with the release
assert(payload == 42); // guaranteed visible
});
producer.join();
consumer.join();
std::vector<std::thread> pool;
for (int t = 0; t < 4; ++t)
pool.emplace_back([] {
for (int i = 0; i < 100000; ++i) hits.fetch_add(1, std::memory_order_relaxed);
});
for (auto& th : pool) th.join();
std::cout << payload << ' ' << hits.load() << '\n';
}
Output: 42 400000. The program also runs clean under ThreadSanitizer (-fsanitize=thread).
Weak answers. “volatile makes a variable thread-safe.” In C++ it does not; it is for memory-mapped hardware, not synchronization.
14. “When do you use a mutex instead of an atomic?”
Why they ask. Can you pick the simple tool when it is right?
Sample answer. “An atomic protects a single variable, so it fits a counter, a flag or a pointer swap. As soon as an invariant spans more than one variable, such as a size and a buffer, I need a mutex, because two separate atomics can be observed in an inconsistent state. I lock with std::scoped_lock, which is RAII again and can lock several mutexes without deadlock, and I keep the critical section short with no I/O or callbacks inside it. std::condition_variable handles waiting for a state change, always with a predicate to survive spurious wakeups.”
Weak answers. “Atomics are always faster, so I avoid mutexes.” Under heavy contention a well-placed mutex can be the faster and safer option.
15. “How do lambdas work, and what can go wrong with captures?”
Why they ask. Dangling captures are a common crash in async code.
Sample answer. “A lambda is an unnamed class with an operator(), and the captures become its data members. [x] copies, [&x] stores a reference, and [=] or [&] capture whatever is used. The main bug is capturing by reference and letting the lambda outlive the scope, for example returning it or posting it to another thread; the reference then dangles. Captured copies are const inside the call unless the lambda is mutable. C++14 added init-captures, which let me move a unique_ptr into a lambda, and generic lambdas with auto parameters.”
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
std::function<int()> make_counter() {
int count = 0;
// [&count] here would dangle once make_counter returns
return [count]() mutable { return ++count; }; // owns its own copy
}
int main() {
auto c = make_counter();
c(); c();
std::cout << c() << '\n';
auto ptr = std::make_unique<int>(7);
auto owner = [p = std::move(ptr)] { return *p * 2; }; // init-capture (C++14)
std::cout << owner() << ' ' << (ptr == nullptr) << '\n';
auto add = [](auto a, auto b) { return a + b; }; // generic lambda
std::cout << add(1, 2) << ' ' << add(1.5, 2.5) << '\n';
std::vector<int> v{5, 3, 9};
int threshold = 4;
auto n = std::count_if(v.begin(), v.end(), [threshold](int x) { return x > threshold; });
std::cout << n << '\n';
}
Output: 3, 14 1, 3 4, 2.
Weak answers. “Lambdas are function pointers.” Only captureless lambdas convert to one.
Rehearse the concurrency and lambda answers with a follow-up in OphyAI Interview Practice, where a question like “what if the callback runs on another thread?” tests whether the answer holds.
16. “How should exceptions and noexcept be used?”
Why they ask. Error handling style varies by team, so they want the trade-offs and the guarantees.
Sample answer. “I throw by value and catch by const reference so I never slice the exception. Code offers one of three guarantees: basic, where invariants hold and nothing leaks; strong, where a failed operation leaves the state unchanged, as in copy-and-swap; or no-throw. noexcept is a promise, not a check: if an exception escapes a noexcept function, std::terminate is called. I mark moves and swaps noexcept because containers query it. Some low-latency and embedded teams disable exceptions and use error codes or std::expected instead, so I ask which style the codebase uses.”
#include <iostream>
#include <stdexcept>
#include <string>
#include <type_traits>
void parse(int x) {
if (x < 0) throw std::invalid_argument("negative");
}
void safe() noexcept { /* promises not to throw */ }
int main() {
try {
parse(-1);
} catch (const std::invalid_argument& e) { // catch by const reference
std::cout << "caught: " << e.what() << '\n';
}
std::cout << noexcept(safe()) << ' ' << noexcept(parse(1)) << '\n';
std::cout << std::is_nothrow_move_constructible_v<std::string> << '\n';
}
Output: caught: negative, 1 0, 1.
Weak answers. “I wrap everything in try/catch(...)”, or not knowing what happens when a noexcept function throws.
17. “What is perfect forwarding?”
Why they ask. It is how emplace_back passes arguments without extra copies.
Sample answer. “Inside a template, T&& where T is deduced is a forwarding reference, not an rvalue reference. Reference collapsing makes T an lvalue reference when I pass an lvalue and a plain type when I pass an rvalue. Inside the function the parameter has a name, so it is an lvalue, and std::forward<T> casts it back to whatever category the caller passed. The rule I follow: std::move for rvalue references, std::forward for forwarding references, and never forward the same argument twice.”
#include <iostream>
#include <memory>
#include <string>
#include <utility>
void take(const std::string&) { std::cout << "lvalue\n"; }
void take(std::string&&) { std::cout << "rvalue\n"; }
template <typename T>
void relay(T&& arg) { // forwarding reference
take(std::forward<T>(arg)); // keeps the value category
}
int main() {
std::string s = "hi";
relay(s); // lvalue
relay(std::string("tmp")); // rvalue
relay(std::move(s)); // rvalue
}
Output: lvalue, rvalue, rvalue.
Weak answers. Treating every T&& as an rvalue reference, or using std::move inside a forwarding function and silently moving from the caller’s lvalue.
18. “What did C++20 add? Talk about ranges, coroutines and modules.”
Why they ask. They want the parts you have used, not a feature list.
Sample answer. “The big four are concepts, ranges, coroutines and modules. Ranges let me pass a container to an algorithm directly, and views compose lazily with the pipe operator, so a filter-transform-take chain does no work until I iterate. Coroutines are functions that can suspend with co_await, co_yield or co_return; the language provides the mechanism and a library provides the types, such as a task for async I/O or a generator. Modules replace textual includes with compiled interfaces, which improves build times and isolation, but build-system and compiler support has lagged: GCC’s status page still lists modules as experimental behind -fmodules.”
#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8};
auto evens_squared = v | std::views::filter([](int x) { return x % 2 == 0; })
| std::views::transform([](int x) { return x * x; })
| std::views::take(3); // lazy: nothing runs yet
for (int x : evens_squared) std::cout << x << ' '; // 4 16 36
std::cout << '\n';
std::ranges::sort(v, std::greater{}); // no begin()/end() pair
std::cout << v.front() << '\n';
}
Output: 4 16 36, then 8.
Weak answers. Claiming modules are fully production-ready on every toolchain, or describing coroutines as threads.
19. “What is std::expected, and what else is new in C++23?”
Why they ask. It shows how you handle errors without exceptions.
Sample answer. “std::expected<T, E> holds either a value or an error, so a function can report failure in its return type without throwing. It is like std::optional with a reason attached, and C++23 gives it monadic operations, and_then, transform and or_else, so I can chain steps without nested ifs. It suits parsing and I/O, where failure is expected. Other C++23 features: std::print and std::println for formatted output built on std::format, deducing this, std::flat_map, std::generator and import std;.”
#include <charconv>
#include <expected>
#include <iostream>
#include <string>
#include <string_view>
enum class ParseError { Empty, NotANumber };
std::expected<int, ParseError> parse_int(std::string_view s) {
if (s.empty()) return std::unexpected(ParseError::Empty);
int value{};
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
if (ec != std::errc{} || ptr != s.data() + s.size())
return std::unexpected(ParseError::NotANumber);
return value;
}
int main() {
for (std::string_view in : {"42", "", "4x"}) {
auto r = parse_int(in);
if (r) std::cout << "ok " << *r << '\n';
else std::cout << "error " << static_cast<int>(r.error()) << '\n';
}
auto doubled = parse_int("21").transform([](int x) { return x * 2; }); // monadic, C++23
std::cout << doubled.value_or(-1) << '\n';
}
Output: ok 42, error 0, error 1, 42. std::print is not shown run here: libstdc++ added it in GCC 14 and this test machine has GCC 13, which already supports std::expected (added in GCC 12).
Weak answers. “It is the same as exceptions.” The point is that the error is part of the type and the caller must handle it.
20. “What is in C++26, and is it finished?”
Why they ask. Senior roles want an accurate status, not hype.
Sample answer. “The committee finished technical work on C++26 at its March 2026 meeting in London Croydon, and the WG21 convenor’s July 2026 business plan says the draft is in its international (DIS) ballot, on schedule for ISO to complete in 2026. The headline features are static reflection, contracts with pre, post and contract_assert, std::execution for the sender/receiver async model, a hardened standard library, and less undefined behavior, including reading an uninitialized local becoming erroneous behavior. Compiler support is uneven: GCC 16 lists reflection behind -freflection, contracts and erroneous behavior, while Clang’s status page still lists those three as not implemented. Work on C++29 has started, with undefined behavior and safety profiles as goals.”
Weak answers. Saying C++26 is “not designed yet”, or claiming every compiler ships reflection today.
21. Live coding: “Implement a simplified unique_ptr.”
Why they ask. It checks RAII, move semantics, deleted copies and noexcept in one 20-minute exercise.
Sample answer. “I hold a raw pointer, delete it in the destructor, delete the copy operations and implement the moves with std::exchange so the source ends up null. Move assignment must handle self-assignment and release the old object first, which reset does. I add get, release, reset, operator*, operator-> and an explicit operator bool so it does not convert to int by accident. Everything except dereferencing is noexcept. Next I would add a custom deleter and the array form.”
#include <iostream>
#include <utility>
template <typename T>
class UniquePtr {
public:
UniquePtr() noexcept = default;
explicit UniquePtr(T* p) noexcept : p_(p) {}
~UniquePtr() { delete p_; }
UniquePtr(const UniquePtr&) = delete;
UniquePtr& operator=(const UniquePtr&) = delete;
UniquePtr(UniquePtr&& o) noexcept : p_(std::exchange(o.p_, nullptr)) {}
UniquePtr& operator=(UniquePtr&& o) noexcept {
if (this != &o) reset(std::exchange(o.p_, nullptr));
return *this;
}
T* release() noexcept { return std::exchange(p_, nullptr); }
void reset(T* p = nullptr) noexcept { delete std::exchange(p_, p); }
T* get() const noexcept { return p_; }
T& operator*() const { return *p_; }
T* operator->() const noexcept { return p_; }
explicit operator bool() const noexcept { return p_ != nullptr; }
private:
T* p_ = nullptr;
};
struct Widget { int id; ~Widget() { std::cout << "~Widget " << id << '\n'; } };
int main() {
UniquePtr<Widget> a(new Widget{1});
UniquePtr<Widget> b = std::move(a);
std::cout << bool(a) << ' ' << b->id << '\n';
b = UniquePtr<Widget>(new Widget{2}); // deletes Widget 1
std::cout << "end\n";
}
Output: 0 1, ~Widget 1, end, ~Widget 2. ASan reports no leaks.
Weak answers. A copy constructor that copies the pointer (a double free), or a move assignment that leaks the old object.
22. Live coding: “Design an LRU cache with O(1) get and put.”
Why they ask. It tests container choice and iterator stability together.
Sample answer. “I keep a std::list of key-value pairs ordered by recency, front most recent, plus an unordered_map from key to list iterator. On get, I look up the iterator and move the node to the front with splice, which is constant time and, importantly, keeps the iterator valid, so the map entry stays correct. On put, I update and splice if the key exists; otherwise, if the cache is full, I erase the back node’s key from the map and pop it, then insert at the front. Both operations are average O(1). I return std::optional<int> from get instead of a magic -1.”
#include <iostream>
#include <list>
#include <optional>
#include <unordered_map>
#include <utility>
class LRUCache {
public:
explicit LRUCache(std::size_t cap) : cap_(cap) {}
std::optional<int> get(int key) {
auto it = index_.find(key);
if (it == index_.end()) return std::nullopt;
items_.splice(items_.begin(), items_, it->second); // O(1), iterators stay valid
return it->second->second;
}
void put(int key, int value) {
if (auto it = index_.find(key); it != index_.end()) {
it->second->second = value;
items_.splice(items_.begin(), items_, it->second);
return;
}
if (items_.size() == cap_) {
index_.erase(items_.back().first);
items_.pop_back();
}
items_.emplace_front(key, value);
index_[key] = items_.begin();
}
private:
std::size_t cap_;
std::list<std::pair<int, int>> items_; // front = most recently used
std::unordered_map<int, std::list<std::pair<int, int>>::iterator> index_;
};
int main() {
LRUCache c(2);
c.put(1, 10); c.put(2, 20);
c.get(1); // 1 is now most recent
c.put(3, 30); // evicts 2
std::cout << c.get(2).has_value() << ' ' << *c.get(1) << ' ' << *c.get(3) << '\n';
}
Output: 0 10 30. Key 2 was evicted.
Weak answers. Using std::vector and an O(n) search, or storing list iterators in the map without knowing which operations invalidate them.
How to Practice These
Run a voice or text mock in OphyAI Interview Practice, which asks follow-up questions and returns a transcript with per-answer feedback, so you find out whether your move semantics answer survives “and what happens if the move constructor throws?”. For live coding rounds, OphyAI Coding Copilot (desktop app, Premium plan, $59 a month, 15 credits a session) snaps the problem window with Cmd/Ctrl+Shift+A, drags a box around part of the screen with Cmd/Ctrl+Shift+S, or transcribes a question the interviewer asks out loud with Space or Cmd/Ctrl+Shift+L, and each answer card shows how it read the problem, what to say first, the code, a dry run with edge cases and the Big O. For the conversational parts of a live video interview, OphyAI Interview Copilot gives real-time answer suggestions on Zoom, Microsoft Teams and Google Meet. Start practicing →
Daily routine: answer four questions aloud, then write one class from memory (a unique_ptr, a ring buffer, an LRU cache) and compile it with -Wall -Wextra -fsanitize=address,undefined. For broader drills, see our coding interview practice page and the coding interview patterns guide.
Frequently Asked Questions
What C++ topics come up most in interviews?
RAII and smart pointers, move semantics and the rule of five, virtual functions and the virtual destructor rule, undefined behavior, templates, STL containers and iterator invalidation, and concurrency come up in most C++ technical screens. Systems, trading and game teams go deeper into memory layout, cache behavior, atomics and lock-free code, and often ask you to build a small container or cache by hand.
Which C++ standard should I prepare for?
Prepare modern C++ from C++11 through C++20 thoroughly, because that is what most production codebases use, and know the main C++23 additions such as std::expected and std::print. For C++26, know the status and headline features (reflection, contracts, std::execution) rather than syntax details, since compiler support is still partial. Ask the recruiter which standard and compiler the team builds with.
Is C++ a good language for coding interviews?
Yes, if it is your strongest language. The standard library has a priority queue, ordered and hashed maps, and fast sorting, and performance is never a concern. The cost is verbosity and a few traps, such as priority_queue being a max-heap by default and integer overflow being undefined. For general algorithm rounds where you choose the language, many candidates pick Python for speed; for systems and trading roles, C++ is often expected.
How are C++ questions different from Java interview questions?
C++ interviews focus on ownership, object lifetime, value versus reference semantics and undefined behavior, because there is no garbage collector or bounds checking by default. Java interviews spend that time on the JVM, garbage collection, collections and concurrency utilities. If you are preparing both, our Java interview questions guide covers the Java side with the same format and tested code.
How do I answer C++ questions without sounding memorized?
Give a one-sentence definition, a short example you can type from memory, and one real bug the concept caused or prevented in your own code: a dangling reference in a lambda, a leak from a shared_ptr cycle, an iterator used after push_back. Interviewers follow up on your example, so choose one you can discuss for two minutes and can compile on a whiteboard.
How long does it take to prepare for a C++ interview?
If you write modern C++ every day, one to two weeks of concept review plus a daily coding problem is a common plan. If you are coming back to C++ from another language or from pre-C++11 code, allow three to four weeks to get comfortable with move semantics, smart pointers and the memory model. These are typical ranges, not a rule; adjust for the role’s level and the number of rounds.
How does OphyAI work in a C++ coding interview?
Rehearse the spoken questions, such as RAII or the memory model, in Interview Practice. For the coding round, Coding Copilot in the desktop app reads the problem with Cmd/Ctrl+Shift+A or a dragged box with Cmd/Ctrl+Shift+S, remembers it for follow-ups, and shows the code with a dry run in an overlay left out of screen sharing that does not take the keyboard from your editor. It is not hidden from a webcam, keystroke history or proctoring software.
Related Guides
- Nvidia interview guide
- AMD interview guide
- Arm interview guide
- Hudson River Trading interview guide
- Jump Trading interview guide
- Optiver interview guide
- Susquehanna (SIG) interview guide
- Citadel interview guide
- Bloomberg interview guide
- Java interview questions
- Python interview questions
- JavaScript interview questions
- Coding interview examples and solutions
- Technical interview prep for software engineers
Sources and verification notes
Sources checked November 2026. Every complete code sample was compiled with g++ 13.3.0 (-std=c++23 -Wall -Wextra -fsanitize=address,undefined) and run; outputs shown are the actual results, and the atomics sample also ran clean under ThreadSanitizer. std::print and C++26 features are described from the sources below, not run. cppreference.com returned HTTP 403 to our tools, so standard wording was checked against the working draft at eel.is. The sample answers are original templates, not questions published by any employer.
- Herb Sutter, C++26 is done! Trip report: March 2026 ISO C++ standards meeting (March 29, 2026): C++26 technical work complete; reflection, contracts,
std::execution, hardened library, no UB for uninitialized local reads. - Herb Sutter, Trip report: June 2026 ISO C++ standards meeting (Brno): first C++29 meeting; UB reduction and profiles aimed at C++29.
- WG21 N5056, Business Plan and Convenor’s Report (2026-07-28): the next 14882 edition is in DIS ballot, on schedule to complete in 2026.
- GCC, C++ Standards Support: modules experimental (
-fmodules); reflection (-freflection), contracts and erroneous behavior in GCC 16. - libstdc++ implementation status:
std::expectedin GCC 12.1,std::printin GCC 14.1,std::flat_mapin GCC 15.1. - Clang, C++ Support: P2996 reflection, P2900 contracts and P2795 erroneous behavior not implemented.
- C++ working draft: [vector.modifiers] and [unord.req.general] (invalidation), [intro.races] (data races are UB), [basic.indet] (erroneous values).
- C++ Core Guidelines: R.1, R.11, R.20, R.22, C.20, C.21, C.35, C.66.
Tags:
Share this article:
Rehearse your answers, then get live help on the call.
Practice free for up to 15 minutes, then use Interview Copilot in the OphyAI desktop app: real-time answer suggestions on Zoom, Teams and Google Meet, in a window hidden from screen sharing.
On your phone? Practice interview answers in the OphyAI app.
Hidden from screen share and recording; a webcam or a person in the room can still see your screen.
Related Articles
22 JavaScript Interview Questions: Closures, Event Loop, this (2026)
Interview Tips
22 JavaScript interview questions with sample answers: closures, the event loop output-order puzzle, this binding, debounce, structuredClone and ES2026.
Read more →
24 Python Interview Questions & Answers (2026): GIL, Decorators, Code
Interview Tips
24 Python interview questions with sample answers: dict hashing, is vs ==, decorators, generators, the GIL vs asyncio, MRO, plus coding tasks and pandas.
Read more →
Java Interview Questions: 18 Answers With Code-Level Samples (2026)
Interview Tips
18 Java interview questions with sample answers: equals and hashCode, HashMap internals, JVM memory, concurrency, streams, records and virtual threads.
Read more →