C++ quant interviews test whether you can reason precisely about programs that manipulate large numerical workloads under reliability and performance constraints. Syntax is the entry ticket; lifetime, ownership, data layout, interfaces, concurrency, and measurement determine the stronger answers.
The goal is not to volunteer every modern language feature. Choose the simplest construct that makes invariants clear, avoids undefined behavior, and fits the performance need. Then demonstrate the choice with tests and a benchmark.
What this guide helps you do
- Explain C++ ownership, lifetime, and value semantics precisely.
- Select STL containers from operations, guarantees, and memory behavior.
- Discuss concurrency and performance without hand-waving.
- Implement numerical code with defensible tolerances and tests.
1. Master lifetime, ownership, and RAII
Know automatic, dynamic, static, and thread storage duration; construction and destruction order; references and pointers; and common routes to dangling objects. RAII binds a resource to an object lifetime so cleanup occurs during normal return and exception unwinding.
Smart pointers express ownership, but they are not a default replacement for every raw pointer. Use unique_ptr for exclusive dynamic ownership, shared_ptr only for genuine shared lifetime, weak_ptr to observe without extending that lifetime, and references or non-owning pointers when the owner is clear and outlives the use.
- Apply the rule of zero when members already manage their resources.
- Know when a user-declared destructor changes generated move operations.
- Return values normally and rely on copy elision rather than premature moves.
- Treat undefined behavior as a correctness failure, not a performance technique.
2. Choose STL tools from required operations
For each container, know lookup, insertion, iteration, invalidation, ordering, and memory characteristics. vector is often the default because contiguous storage gives good locality, but stable references, ordered queries, or keyed lookup may justify another choice.
Prefer algorithms that state intent and separate policy from mechanism. In interviews, mention comparator requirements, iterator categories, invalidation, and what happens with duplicates or missing keys.
| Container | Strength | Watch for |
|---|---|---|
| vector | Contiguous storage and fast iteration | Reallocation invalidates pointers and iterators |
| deque | Efficient insertion at both ends | Non-contiguous blocks and different locality |
| map | Ordered keys and logarithmic operations | Node overhead and poorer locality |
| unordered_map | Expected constant-time keyed access | Hash quality, rehashing, memory, and no ordering |
3. Use templates and types to protect invariants
Templates enable zero-overhead generic numerical components, but diagnostics and compile times can become costs. Understand deduction, overload resolution, specialization at a practical level, and the purpose of concepts or constraints. Avoid template cleverness that makes a pricing interface harder to reason about.
Strong domain types can prevent unit, currency, date, and sign errors. Const-correctness, small interfaces, explicit conversions, and clear ownership make code review and model validation easier.
4. Connect performance to data movement
CPU time in numerical code is often shaped by memory access, allocation, branching, and vectorization. Contiguous structures of simple values can outperform pointer-rich designs even when asymptotic complexity is identical. Benchmark with optimized builds and representative data.
Know the difference between latency and throughput, and report distributions rather than a single best timing. A useful optimization answer preserves a reference implementation and accuracy tests so a faster result cannot silently change the model.
- Remove repeated allocation and invariant calculations from hot loops.
- Improve locality and access patterns before adding threads.
- Use profilers and hardware counters to confirm the bottleneck.
- Measure compiler settings, warm-up, input distribution, and variance.
5. Prepare concurrency and numerical edge cases
Understand the C++ memory model, data races, mutexes, condition variables, atomics, futures, and task decomposition. Atomics provide ordering choices, not automatic algorithm correctness. In a pricing engine, independent paths or trades may parallelize well, while shared aggregation and memory bandwidth can limit scaling.
For numerics, discuss conditioning, cancellation, accumulation, special values, tolerance design, and reproducibility. Standard floating-point arithmetic is deterministic only under a fixed operation order and environment; parallel reductions may change the final bits.
Check your understanding
Test yourself
Five questions, from warm-up to hard. Try each one before you open the answer.
Warm-up · Question 1
What does this print, and why? unsigned int a = 3; int b = -1; std::cout << (b < a);
Show the answer
It prints 0 (false). b is converted to unsigned before the comparison, so −1 becomes 4,294,967,295, which is larger than 3. Compilers warn with -Wsign-compare.
- Mixed int and unsigned int operands go through the usual arithmetic conversions: the int becomes unsigned.
- −1 as a 32-bit unsigned value is 2³² − 1 = 4,294,967,295.
- 4,294,967,295 < 3 is false, so the expression prints 0.
- Fix: keep both signed, or test b < 0 first. The same trap appears when you compare an int index with v.size().
Warm-up · Question 2
std::vector<int> v = {1, 2, 3}; int& r = v[0]; v.push_back(4); std::cout << r; What is wrong with this code?
Show the answer
push_back may reallocate the buffer (with GCC the capacity grows from 3 to 6), so r refers to freed memory. Reading it is undefined behaviour.
- A vector built from 3 values usually has a capacity of exactly 3.
- push_back needs a 4th slot, so the vector allocates a bigger buffer, moves the elements across and frees the old one.
- r still points into the old buffer: a dangling reference. AddressSanitizer reports heap-use-after-free.
- Fix: call v.reserve(4) first, keep an index instead, or take the reference after the push_back.
Step up · Question 3
int n = 100000; long long sq = n * n; Why can sq hold the wrong value, even though long long is big enough for 10¹⁰?
Show the answer
n * n is computed as an int before the assignment, and 10¹⁰ overflows a 32-bit int. Signed overflow is undefined behaviour. Write static_cast<long long>(n) * n.
- The type of n * n depends only on its operands: both are int, so the product is an int.
- The largest 32-bit int is 2,147,483,647, far below 10,000,000,000.
- Signed overflow is undefined; in practice you often see 1,410,065,408 (the value modulo 2³²).
- Widen one operand before multiplying. UBSan (-fsanitize=undefined) catches this in tests.
Step up · Question 4
A Book class holds a std::vector<double> and declares ~Book() {} but no copy or move operations. Does Book b2 = std::move(b1); move the vector or copy it?
Show the answer
It copies. A user-declared destructor stops the compiler generating a move constructor, so std::move falls back to the copy constructor. Drop the empty destructor (rule of zero).
- std::move only casts b1 to an rvalue; it does not move anything by itself.
- With a user-declared destructor, no implicit move constructor is declared, but the implicit copy constructor still is.
- The rvalue binds to const Book&, so the whole vector is copied and b1 keeps its data.
- Fix: remove the empty destructor so the compiler generates all five members, or declare the move operations with = default.
Hard · Question 5
float s = 0.0f; for (int i = 0; i < 10000000; ++i) s += 0.1f; With GCC this prints 1087937, not 1000000. Explain the drift and give two fixes.
Show the answer
As s grows, the gap between floats widens. Above 524,288 each + 0.1f rounds to + 0.125, so the sum runs about 9% high. Fix: a double accumulator, or Kahan or pairwise summation.
- A float has a 24-bit significand, so the gap between neighbouring floats doubles each time the value passes a power of 2.
- Between 524,288 (2¹⁹) and 1,048,576 (2²⁰) the gap is 0.0625, so s + 0.1f rounds to s + 0.125. Above 2²⁰ the gap is 0.125, with the same result.
- From about the halfway point, every add counts 0.125 instead of 0.1, so the total overshoots to 1,087,937.
- Adding the same float inputs into a double gives 1,000,000.0149. Kahan or pairwise summation also work. Note that parallel sums change the order, and so the last bits.
More practice: 80 worked interview questions by topic · the daily desk question
Plain language
Words on this page
- RAII
- Resource Acquisition Is Initialisation: a resource is taken in a constructor and released in the destructor, so cleanup happens automatically when the object goes out of scope.
- Move semantics
- Handing an object's resources, such as a vector's buffer, to another object instead of copying them. The source is left valid but usually empty.
- Iterator invalidation
- When a container operation makes existing iterators, pointers or references unsafe to use. For example, a vector's push_back can reallocate and invalidate all of them.
- Undefined behaviour
- Code whose result the C++ standard does not define, such as signed overflow or reading freed memory. It may seem to work, then fail with another compiler or flag.
- Usual arithmetic conversions
- The rules that bring mixed operand types to a common type before an operation. Comparing an int with an unsigned int converts the int, so −1 becomes a huge value.
Practise aloud
Interview drills with answer direction
Question 1
What problem does RAII solve?
Answer direction: RAII ties resource acquisition and release to object lifetime, making cleanup deterministic across normal returns and exceptions. It applies to memory, files, locks, sockets, and other resources.
Question 2
Why can vector outperform list?
Answer direction: Vector has contiguous storage, less per-element overhead, fewer allocations, and better cache and prefetch behavior. List helps when stable iterators and known-position insertion dominate, but traversal is costly.
Question 3
What is a data race?
Answer direction: It is conflicting concurrent access to the same memory location, with at least one write, without the required synchronization. In C++, a data race causes undefined behavior.
Question 4
How would you design a parallel Monte Carlo engine?
Answer direction: Partition independent paths, use thread-local state and random streams, minimize shared writes, combine results carefully, preserve reproducibility metadata, and verify confidence intervals and scaling.
Question 5
When should shared_ptr be avoided?
Answer direction: Avoid it when ownership is actually exclusive or externally managed, when cycles may form, or when atomic reference-count overhead and unclear lifetime obscure the design. Prefer the narrowest ownership model.
Turn reading into practice
A focused study plan
- Block 1
Semantics
Write small programs for lifetime, copying, moving, exceptions, smart pointers, and undefined-behavior diagnosis.
- Block 2
Library
Practise containers, algorithms, iterators, lambdas, and complexity with market-shaped data.
- Block 3
Systems
Profile allocation and locality, then implement safe task parallelism and benchmark scaling.
- Block 4
Numerics
Build a small pricer with invariants, analytical cases, tolerance policy, and performance tests.
Self-review
Frequent mistakes to catch early
- Using shared_ptr as a universal memory-management answer.
- Quoting Big-O while ignoring allocation and locality.
- Calling atomics lock-free without discussing memory ordering or progress guarantees.
- Benchmarking debug builds or changing numerical results without accuracy tests.
Continue with structured practice
Relevant Desk2Quant resources
C++ for Quants: Desk-Ready Notes
Use desk-focused notes and exercises to deepen modern C++ semantics and quant implementation patterns.
Explore this resourceNumerical Methods for Quants: The Master Field Manual
Apply C++ decisions to root finding, interpolation, PDE, Monte Carlo, and calibration workloads.
Explore this resourceUltimate Industry-Grade Quant Project Pack
Choose a substantial project and add C++ tests, benchmarks, profiling evidence, and design documentation.
Explore this resourceKeep building
Related quant finance guides
Common questions
Frequently asked questions
What C++ topics are asked in quant interviews?
Common topics include lifetime, RAII, pointers and references, value and move semantics, STL, templates, memory layout, concurrency, performance, floating-point arithmetic, testing, and numerical implementation.
Which C++ standard should I prepare?
Use the standard named by the employer when available. Otherwise prepare the modern core shared across C++17 and later, and be ready to distinguish a language feature from a compiler or library extension.
Do I need low-latency C++ for every quant role?
No. Pricing libraries, risk engines, research infrastructure, and execution systems have different performance goals. Learn sound measurement and memory behavior, then specialize to the team's latency or throughput needs.
How should I practise C++ for quant interviews?
Combine short semantics exercises, timed algorithms, debugging, code review, profiling, and one tested numerical project. Explain ownership, complexity, numerical error, and benchmark design aloud.