C++ Interview Questions

Dan Lee's profile image
Dan LeeData & AI Lead
Last update
C++ Interview Questions

C++ interviews for quant developer, systems and ML infrastructure roles rarely ask you to recite syntax. They hand you twenty lines that compile and ask what happens. Who owns this buffer? When does this destructor run? Why did std::vector copy instead of move, and why does this loop pass on x86 and fail on ARM? The language gives you control over memory and time, and the interview checks whether you know what each line costs.

Candidates slip in predictable places. They treat std::move as if it moved something, assume shared_ptr is thread-safe end to end, describe undefined behavior as "it might crash", and pick a memory order without being able to say what it guarantees. Strong answers state the rule, then name the practical check that proves it: a sanitizer, a static_assert or a compiler warning.

The 31 questions below are grouped into five areas: object lifetime and move semantics, smart pointers, undefined behavior, the STL with templates and compile-time code, and concurrency with performance. Each has a worked answer, most include C++20 code we compiled and ran with Clang, and the page ends with prep advice, a short quiz and an FAQ.

Advanced31 questions

C++ Interview Questions

Practice C++ interview questions on RAII, move semantics, smart pointers, undefined behavior, the STL, templates, concurrency and performance, with worked answers and code.

Software EngineerQuantitative DeveloperMachine Learning Infrastructure EngineerSystems EngineerEmbedded Software Engineer

Object Lifetime, RAII and Move Semantics

Every C++ interview loop gets to the question of who owns a resource and when it is released. Lifetime bugs (leaks, double frees, dangling references) are the ones that take down production services, and your answer shows whether you think in objects or in raw memory.

The idea that matters most: a destructor runs at a known point, at the end of a scope or during stack unwinding, so every resource should belong to an object. Move semantics are an optimization on top of that. std::move is only a cast, and the move constructor decides what actually happens.

Object Lifetime, RAII and Move Semantics

A function opens a file with fopen, has four return paths and calls code that can throw. Reviewers keep finding leaked file handles in production. How would you restructure it?

EasyObject Lifetime, RAII and Move Semantics

Sample Answer

Tie the handle to an object whose destructor closes it. That is RAII: acquire in a constructor, release in a destructor, and rely on the language to run destructors on every exit from the scope, including stack unwinding after an exception. A std::unique_ptr with a custom deleter does it in a few lines. Use a deleter struct rather than &std::fclose: since C++20, taking the address of most standard library functions is unspecified, and an empty deleter type keeps sizeof(File) equal to a raw pointer. unique_ptr never calls the deleter on a null pointer. One caveat: if an exception escapes main with no handler, std::terminate runs, and whether the stack is unwound first is implementation-defined.

C++
1#include <cstdio>
2#include <memory>
3#include <stdexcept>
4struct FileCloser {
5    void operator()(std::FILE* f) const noexcept { std::fclose(f); }
6};
7using File = std::unique_ptr<std::FILE, FileCloser>;
8File open_or_throw(const char* path) {
9    File f(std::fopen(path, "r"));
10    if (!f) throw std::runtime_error("cannot open file");
11    return f;  // closed on every later return or throw
12}
13static_assert(sizeof(File) == sizeof(std::FILE*));
Learn this in the Modern C++ course

Smart Pointers and Ownership

Smart pointers are where ownership design meets the type system, so interviewers use them to see whether you can express who frees what in a function signature. Expect questions on what each pointer costs, what a shared_ptr control block holds, and how a reference cycle leaks.

Default to std::unique_ptr and plain references. Use std::shared_ptr only when ownership is genuinely shared and the last owner is not known in advance, because every copy is an atomic counter update and shared ownership makes destruction order harder to reason about.

Smart Pointers and Ownership

You are designing an order book where the gateway creates each Order and the book destroys it when it is filled or cancelled. A colleague proposes std::shared_ptr<Order> everywhere to be safe. What would you use, and what does each choice cost?

EasySmart Pointers and Ownership

Sample Answer

Each order has exactly one owner at a time, the book, so std::unique_ptr<Order> fits. With the default deleter it is the size of a raw pointer (8 bytes on a 64-bit build) and compiles to the same code as new and delete. A std::shared_ptr is 16 bytes, a pointer to the object plus a pointer to its control block, and every copy or destruction performs an atomic increment or decrement on a shared counter. On a hot path with several threads touching the same orders, that traffic shows up in profiles. Functions that only read an order should take const Order& or const Order*, since they play no part in ownership. Pass std::unique_ptr by value only to a function that takes ownership.

Learn this in the Modern C++ course

Undefined Behavior and Debugging

Undefined behavior is the signature hazard of C++, and interviewers for latency-sensitive and infrastructure roles probe it directly. They show code that seems to work, then ask what the optimizer is allowed to do with it. The compiler assumes UB never happens and transforms the program on that assumption, which is why these bugs appear only in release builds.

The most useful habit is knowing which tool catches which bug. AddressSanitizer finds out-of-bounds access and use-after-free, UndefinedBehaviorSanitizer finds overflow and invalid shifts, ThreadSanitizer finds data races, and standard library hardening turns container bounds errors into immediate traps.

Undefined Behavior and Debugging

std::vector<int> v(5); int x = v[10]; runs without any error and produces a random number. Why is there no exception, and how would you catch this class of bug across a large codebase?

EasyUndefined Behavior and Debugging

Sample Answer

operator[] does no bounds checking. Reading index 10 of a 5-element vector is undefined behavior, and in practice it reads whatever sits in memory past the buffer; a local build printed 79127920. v.at(10) checks and throws std::out_of_range, at the cost of a compare and branch per access. To catch these bugs without rewriting call sites, run tests under AddressSanitizer (-fsanitize=address), and turn on the standard library's hardening: -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST for libc++, or -D_GLIBCXX_ASSERTIONS for libstdc++. With the libc++ fast mode, the same program stopped with a trap instead of printing garbage. The fast mode is designed to be cheap enough to keep in production builds.

Learn this in the Modern C++ course

STL Containers, Templates and Compile-Time Code

Interviewers use the standard library to test whether you know what your data structures cost on real hardware, and templates to test whether you can write generic code that other engineers can call without reading it. Questions range from picking a container to explaining why a template error runs for two hundred lines.

Carry one idea into every container answer: memory layout. A contiguous std::vector wins most benchmarks against node-based containers because the CPU prefetcher can stream through it, even in cases where the big-O analysis favors the alternative.

STL Containers, Templates and Compile-Time Code

You need a container for 100,000 price levels with frequent full iteration and occasional inserts in the middle. A colleague suggests std::list because insertion is O(1). What do you choose?

EasySTL Containers, Templates and Compile-Time Code

Sample Answer

Start with std::vector and measure. std::list gives O(1) insertion only when you already hold an iterator to the position. Finding that position is an O(n) walk through nodes scattered across the heap, usually a cache miss per node, and each element carries two extra pointers (16 bytes). A vector stores elements contiguously, so a scan streams through cache lines and the hardware prefetcher keeps up, and the O(n) shift on insert moves contiguous memory (a memmove for trivially copyable types). For sorted levels, a sorted vector searched with std::lower_bound is a common choice, as is std::map when inserts dominate. Pick std::list when you need iterators that stay valid across inserts and erases, or O(1) splice.

Learn this in the Modern C++ course

Concurrency and Performance

Concurrency questions separate engineers who have shipped multithreaded C++ from those who have only read about it. Trading and ML infrastructure interviews ask about data races, lock design and memory ordering, then move to performance: cache lines, allocations and the price of an indirect call.

One rule anchors the whole area. A data race, meaning two threads touching the same memory with at least one writing and no synchronization, is undefined behavior. Every fix, whether a mutex, an atomic or a queue, works by creating a happens-before relationship between the write and the read.

Concurrency and Performance

Two threads each increment a shared long counter one million times. The final value is usually below two million. Explain, and fix it.

EasyConcurrency and Performance

Sample Answer

++counter is a load, an add and a store. Two threads interleave those steps and lose updates, and because unsynchronized concurrent writes are a data race, the behavior is undefined rather than merely inaccurate. ThreadSanitizer flagged it on the first run, and three plain runs all came up short. For a counter, use std::atomic<long> with fetch_add. A statistics counter that nothing else synchronizes on can use std::memory_order_relaxed, which keeps each increment atomic but orders no other memory. For updates that touch several fields, use a std::mutex with std::lock_guard or std::scoped_lock. C++20's std::jthread joins in its destructor, so a forgotten join() no longer ends in std::terminate.

C++
1#include <atomic>
2#include <thread>
3
4int main() {
5    std::atomic<long> hits{0};   // a plain long here is a data race
6    auto work = [&] {
7        for (int i = 0; i < 1'000'000; ++i)
8            hits.fetch_add(1, std::memory_order_relaxed);
9    };
10    {
11        std::jthread a(work), b(work);
12    }   // both joined here
13    return hits.load() == 2'000'000 ? 0 : 1;
14}
Learn this in the Modern C++ course

How to Prepare for C++ Interviews

Compile every practice answer with sanitizers

Build your practice code with -fsanitize=address,undefined and, for threaded code, a separate -fsanitize=thread build. Interviewers value a candidate who says how they would prove a bug exists. The Undefined behavior and sanitizers lesson walks through which tool catches which class of bug.

Know the special member rules without notes

Be able to say which special members the compiler generates when you declare a destructor, a copy constructor or a move constructor, and why a missing noexcept turns vector growth into copies. Work through The rule of three, five and zero and Move semantics until you can write a resource-owning class from memory.

Implement the standard containers yourself

Writing a small vector and shared_ptr from scratch is the fastest way to understand growth policy, exception guarantees and control blocks, and both are common live-coding prompts. Try Implement a vector and Implement shared_ptr, then compare your version against what the library does.

Explain memory ordering with one concrete example

You do not need every memory order. You need one example you can draw on a whiteboard: a payload published with a release store and read after an acquire load, plus why relaxed is wrong there. The Atomics and memory order lesson builds exactly that example step by step.

Practice reading code for bugs, not just writing it

Many C++ rounds hand you working-looking code and ask what is wrong. Practice spotting dangling references, iterator invalidation and missing locks in under a minute. Find the bug in this C++ code is a set of exercises built in that format.

How Ready Are You for C++ Interviews?

1 / 6
Move Semantics

Your class declares a destructor and nothing else. What happens when you std::move an instance into another?

Frequently Asked Questions

Is C++ still asked in software engineering interviews in 2026?

Yes, in specific places. Trading firms, game studios, databases, browsers, embedded systems and ML infrastructure teams (inference servers, CUDA kernels, framework internals) still run C++-specific rounds. General product engineering roles usually let you choose a language, and most candidates pick Python or Java. If the job description lists C++ as the main language, expect at least one round on memory, lifetime and performance, not just algorithms written in C++ syntax.

Which C++ standard should I know for interviews?

Treat C++17 as the baseline and know the main C++20 features: concepts, ranges, std::span, std::jthread, consteval and constinit. Awareness of C++23 helps, for example std::expected and std::print, but few codebases rely on it heavily yet. Interviewers care less about the newest feature than about the fundamentals that have not changed since C++11: RAII, move semantics, value categories and the memory model.

How are C++ interviews for quant developer roles different?

Quant developer interviews lean harder on latency. Expect questions about cache behavior, false sharing, allocation on the hot path, branch prediction, virtual dispatch cost and lock-free queues, often with a follow-up asking how you would measure the effect. Some firms add a debugging round where you find undefined behavior in a short program. Algorithm rounds still happen, but the C++ round is usually where the hiring decision is made.

How long does it take to prepare for a C++ interview?

If you write C++ at work, two to four weeks of focused practice is typical: one week on lifetime, moves and smart pointers, one on the STL and templates, one on concurrency and performance, plus mock questions throughout. Coming from Python or Java, plan on six to ten weeks, because ownership and undefined behavior take time to internalize. Writing small programs and running them under sanitizers speeds this up more than reading does.

Do I need template metaprogramming for C++ interviews?

Rarely in depth. You should be able to write a function template and a class template, explain why templates live in headers, constrain a template with a concept, and read a variadic template with a fold expression. Questions about SFINAE tricks or type-list metaprogramming show up mainly for library and compiler teams. For most roles, time spent on move semantics and concurrency pays off more.

Which compiler and flags should I practice with?

Use a recent GCC or Clang with -std=c++20 -Wall -Wextra, and keep a debug build with -fsanitize=address,undefined -g. Add a separate ThreadSanitizer build for threaded code. Get comfortable reading the assembly a small function compiles to, because interviewers sometimes ask what a loop compiles to. On a Mac, Apple Clang ships libc++, whose string and container layouts differ from libstdc++ on Linux, so say which library you mean.

Dan Lee's profile image

Written by

Dan Lee

Data & AI Lead

Dan is a seasoned data scientist and ML coach with 10+ years of experience at Google, PayPal, and startups. He has helped candidates land top-paying roles and offers personalized guidance to accelerate your data career.

Connect on LinkedIn