C++ interview questions and answers for developers
C++ interview questions are mostly about object lifetime: who owns a resource, when it is destroyed, and what happens when it is copied or moved. Expect RAII and smart pointers, the rule of zero, three and five, move semantics, virtual functions and vtables, templates, STL containers with iterator invalidation, undefined behavior and const correctness. The best answers explain the ownership rule first and then point to a line of code that breaks it.
By Evin JohnPublished 9 min read
Where C++ interviews happen and what they look like
C++ is the working language in game engines, trading systems, embedded and automotive software, browsers, databases and high-performance libraries. Interview loops reflect that. You get a concept screen that probes lifetime and memory, a coding round in C++ where the interviewer watches your use of the standard library, and for experienced roles a deep dive into performance, concurrency or a bug that only appeared in release builds. Many candidates prepare data structures and forget that interviewers will ask why their code is safe.
- Concept screenPointers and references, const, virtual destructors, smart pointers, what
std::moveactually does. Short answers with a precise term win here. - Coding in modern C++Algorithms or a small class such as an LRU cache or a ring buffer. Use containers and algorithms from the standard library instead of raw arrays and manual loops where they fit.
- Code review or debuggingA snippet with a dangling reference, a missing virtual destructor or an erase inside a loop. Name the bug, the rule, and the fix.
- Systems discussionCache-friendly layout, allocation in hot paths, threads and atomics, or how a build and link step can fail.
C++ fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Reference or pointer: how are they different? | Indirection | A reference must be bound at creation, cannot be reseated and is never meant to be null. A pointer can be null, reassigned and used for arithmetic. Prefer references for parameters that must exist, pointers when absence is a valid state. |
Read these aloud: const int* p, int* const p, const int* const p. | const placement | Pointer to const int, const pointer to int, and const pointer to const int. Reading right to left from the name helps. |
| What is a const member function? | const correctness | It promises not to change the object's observable state, so it can be called on const objects and references. mutable members are the escape hatch for caches and mutexes. |
| Stack versus heap allocation? | Storage duration | Automatic objects are destroyed at the end of their scope with no extra work. Dynamic objects live until something frees them, which is why ownership must be explicit. |
| What does new do that malloc does not? | Object creation | new allocates and runs the constructor; delete runs the destructor and frees. Mixing them with malloc and free, or delete with delete[], is undefined behavior. |
| Why does a base class need a virtual destructor? | Polymorphic deletion | Deleting a derived object through a base pointer without one is undefined behavior; in practice the derived destructor is skipped and its resources leak. |
| What is the difference between struct and class? | Language rules | Only the default access: public for struct, private for class, including for inheritance. Convention uses struct for plain data. |
What is inline used for today? | Linkage | Its main job is the one-definition rule: an inline function or variable may be defined in a header included by many files. Whether the call is actually inlined is the compiler's choice. |
RAII, smart pointers and the rule of zero, three and five
RAII ties a resource to an object's lifetime: the constructor acquires it, the destructor releases it, and the language runs destructors on every exit path, including exceptions. Smart pointers, std::vector, std::lock_guard and file stream classes all follow this idea. Interviewers often ask you to write a class that owns raw memory, then ask what you would write instead.
class Buffer {
public:
explicit Buffer(std::size_t n) : size_(n), data_(new int[n]{}) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer& other)
: size_(other.size_), data_(new int[other.size_]) {
std::copy(other.data_, other.data_ + size_, data_);
}
Buffer(Buffer&& other) noexcept
: size_(std::exchange(other.size_, 0)),
data_(std::exchange(other.data_, nullptr)) {}
// Copy-and-swap: one by-value operator covers copy and move assignment.
Buffer& operator=(Buffer other) noexcept {
std::swap(size_, other.size_);
std::swap(data_, other.data_);
return *this;
}
private:
std::size_t size_;
int* data_;
};
// Rule of zero: a member owns the memory, so nothing special is written.
class SimpleBuffer {
public:
explicit SimpleBuffer(std::size_t n) : data_(n) {}
private:
std::vector<int> data_;
};- State the rule of three, five and zero. If you write a destructor, copy constructor or copy assignment, you probably need all three. Add the move constructor and move assignment for five. Better still, hold resources in members that manage themselves and write none: the rule of zero.
- unique_ptr versus shared_ptr? unique_ptr is sole ownership with no overhead beyond the pointer, movable but not copyable. shared_ptr counts owners with an atomic reference count and a separate control block. Default to unique_ptr and share only when ownership truly is shared.
- Why prefer make_shared and make_unique? No naked new, exception safety in function arguments, and make_shared puts the object and control block in one allocation.
- What problem does weak_ptr solve? A cycle of shared_ptrs never reaches a count of zero, so it leaks. Making the back edge weak breaks the cycle; you call lock() to get a temporary shared_ptr when you need the object.
- When is a raw pointer still fine? As a non-owning, nullable view of an object someone else owns, such as a parameter. The ownership rule is in the type of the owner, not in every pointer.
- What happens if a destructor throws? Destructors are noexcept by default, so throwing calls std::terminate. Log and swallow inside destructors instead.
struct Parent;
struct Child {
std::weak_ptr<Parent> parent; // observes, does not own
};
struct Parent {
std::shared_ptr<Child> child; // owns
~Parent() { std::cout << "parent freed\n"; }
};
{
auto p = std::make_shared<Parent>();
p->child = std::make_shared<Child>();
p->child->parent = p;
std::cout << p.use_count() << "\n"; // 1
} // prints "parent freed"Move semantics and value categories
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does std::move do? | Casts | Nothing at runtime. It casts its argument to an rvalue reference so overload resolution can pick a move constructor or move assignment. The move happens there, if it happens at all. |
| What state is a moved-from object in? | Library guarantees | Valid but unspecified for standard types. You may assign to it or destroy it; do not read its value and expect anything. |
| Why mark a move constructor noexcept? | Strong exception safety | std::vector moves elements during reallocation only if the move cannot throw; otherwise it copies to keep its guarantee. A missing noexcept silently costs copies. |
Should you write return std::move(local);? | Copy elision | Usually not. Returning a local by name already moves or elides the copy, and the explicit move can block elision. |
| What is a forwarding reference? | Templates | T&& where T is deduced. It binds to lvalues and rvalues, and std::forward<T> passes the original category on to the next call. |
| lvalue, prvalue, xvalue: can you place examples? | Value categories | A named variable is an lvalue, a temporary such as a + b is a prvalue, and the result of std::move is an xvalue. The categories decide which overloads bind. |
Virtual functions, vtables and inheritance
struct Shape {
virtual ~Shape() = default;
virtual std::string name() const { return "shape"; }
};
struct Circle : Shape {
std::string name() const override { return "circle"; }
};
void byValue(Shape s) { std::cout << s.name() << "\n"; }
void byRef(const Shape& s) { std::cout << s.name() << "\n"; }
Circle c;
byValue(c); // shape: only the base subobject was copied
byRef(c); // circle: dispatched through the vtable- How is virtual dispatch usually implemented? Each polymorphic class has a table of function pointers, and each object holds a hidden pointer to its class's table. A virtual call loads that pointer, indexes the table and calls through it. The standard does not require vtables, but mainstream compilers use them.
- Why can a virtual call cost more than the extra load? It usually prevents inlining, and an unpredictable target can hurt branch prediction. The compiler can devirtualize when it knows the exact type, for example with
final. - What happens when a constructor calls a virtual function? It runs the version for the class being constructed, not the most derived one, because the derived part does not exist yet.
- What do override and final give you? override makes the compiler reject a function that does not actually override anything, such as one with a slightly different signature. final stops further overriding or derivation.
- What is the diamond problem and how does virtual inheritance help? Two bases that share a grandparent give the derived class two copies of it. Virtual inheritance keeps one shared copy at the cost of more complex construction.
- Static versus dynamic polymorphism? Templates and overloads are resolved at compile time; virtual functions at runtime. CRTP is a common way to get interface-like reuse with no virtual calls.
Templates, STL containers and iterator invalidation
| Question | What it tests | What a strong answer shows |
|---|---|---|
| vector, deque or list: which do you reach for? | Containers | vector by default: contiguous memory and cache-friendly scans beat a linked list's O(1) insert in most real workloads. list only when you must keep iterators stable through many middle insertions. |
| map versus unordered_map? | Associative containers | map is a balanced tree with ordered iteration and O(log n) lookup. unordered_map is a hash table with average O(1) lookup, no order, and a rehash that invalidates iterators. |
| When does push_back invalidate references into a vector? | Invalidation | Whenever size would exceed capacity, the vector reallocates and every pointer, reference and iterator into it becomes invalid. reserve avoids it when you know the size. |
| Why are templates usually defined in headers? | Instantiation | The compiler needs the full definition to generate code for each set of template arguments it sees, in every file that uses them. |
| What are C++20 concepts for? | Constraints | Named requirements on template arguments, which give readable errors at the call site instead of pages of failure deep inside the template. |
| What does emplace_back add over push_back? | Construction in place | It forwards arguments to the element's constructor inside the container, skipping a temporary. With an existing object of the right type there is little difference. |
std::vector<int> v{1, 2, 3, 4, 5, 6};
for (auto it = v.begin(); it != v.end();) {
if (*it % 2 == 0) it = v.erase(it);
else ++it;
}
// C++20 one-liner with the same result:
// std::erase_if(v, [](int x) { return x % 2 == 0; });Undefined behavior questions
Undefined behavior means the standard places no requirement on what happens, and optimizers rely on it not occurring. That is why a bug can vanish in a debug build and appear with optimizations on. Interviewers like to show a snippet and ask what is wrong; never claim what it prints.
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4); // may reallocate
std::cout << first; // dangling reference if it did
int big = INT_MAX;
big + 1; // signed overflow
// Dangling: the temporary dies at the return. Compilers warn,
// and the C++26 draft rules make it a compile error.
const std::string& name() { return std::string("tmp"); }- Name common sources of undefined behavior. Out-of-bounds access, use after free, double delete, signed integer overflow, reading an uninitialized variable, a data race, and violating strict aliasing.
- How do you find it in a real codebase? Turn on warnings, build test runs with AddressSanitizer and UndefinedBehaviorSanitizer, use ThreadSanitizer for races, and add fuzzing for parsers.
- Unsigned overflow too? No. Unsigned arithmetic wraps modulo two to the power of the width by definition. Only signed overflow is undefined.
- What is a data race in C++ terms? Two threads access the same memory without synchronization and at least one writes. The fix is a mutex or std::atomic, not volatile.
Senior and scenario questions
| Scenario | What it tests | What a strong answer shows |
|---|---|---|
| A crash appears only in the optimized release build. | UB and tooling | Suspect undefined behavior that the optimizer exploited. Reproduce with sanitizers, then bisect the change that exposed it. |
| A hot loop is slower than expected after a refactor to a vector of pointers. | Data layout | Pointer chasing breaks cache locality. Store objects contiguously, split hot and cold fields, measure with a profiler before and after. |
| A shared_ptr-heavy service spends time in atomic operations. | Ownership cost | Copying shared_ptr touches an atomic count. Pass by const reference or raw pointer when you are not taking ownership. |
| Two threads update a counter and the total is wrong. | Concurrency | A data race. Use std::atomic for a single counter, a mutex for compound state, and explain memory ordering only as deep as needed. |
| A header change rebuilds the whole project. | Build hygiene | Forward declarations, the pimpl idiom, fewer includes in headers, and modules where the toolchain supports them. |
Fictional example
- Calling delete works only if every path through the code reaches it, including early returns and exceptions, and only if exactly one place is responsible. In a parser I maintained, an error path returned before freeing a node, and the leak only showed up on malformed files. Switching the node to unique_ptr made the ownership visible in the type and let the destructor clean up on every path, so the fix deleted lines instead of adding them. I still use raw pointers, but only as non-owning views, and I reach for shared_ptr only when two parts of the program truly share lifetime.
Three-week C++ preparation plan
- Week 1, ownership: write the Buffer class above from memory, then replace it with the rule-of-zero version. Add a weak_ptr back reference and confirm with a destructor print that nothing leaks.
- Week 1, const and references: for each const position, write a line that compiles and one that does not, and explain the error message.
- Week 2, language depth: move semantics with noexcept, slicing, virtual destructors, constructors calling virtual functions. Build each with sanitizers on.
- Week 2, the standard library: solve ten algorithm problems using only standard containers and algorithms, then state which operations invalidate iterators in each container you used.
- Week 3: one timed design such as an LRU cache or a thread-safe queue, then a review pass looking for undefined behavior, copies you did not intend and missing tests.
If you are weighing C++ against its newer neighbors, Rust interview questions cover the same ownership ideas enforced by the compiler, and C# interview questions show the garbage-collected side of lifetime. For the full loop beyond the language, see software engineer interview questions.
Natively, an AI interview assistant for Mac and Windows, can sit in on a mock C++ round and keep a transcript, which makes it easy to spot where an explanation of move semantics turned into guesswork. While you practice it can read a snippet or problem from a screenshot, give a hint, or outline an approach, and with Pro or the free trial it can draw on the résumé and job description you add. Afterward the session and its notes are there to review.
Questions people ask
What C++ questions are asked in interviews?
Most rounds cover references versus pointers, const correctness, RAII and smart pointers, the rule of zero, three and five, move semantics, virtual functions and destructors, STL containers and iterator invalidation, and common undefined behavior.
How should I answer C++ memory management questions?
Start from ownership: say who owns the resource and when it is released. Then show the modern tool, usually unique_ptr or a container, and mention weak_ptr for cycles and raw pointers only as non-owning views.
What C++ topics matter for experienced developers?
Move semantics and noexcept, undefined behavior and sanitizers, data layout and cache effects, concurrency with atomics and mutexes, template constraints with concepts, and build times.
Is modern C++ expected in interviews?
Usually yes. Interviewers expect smart pointers instead of manual delete, standard algorithms and containers, auto and range-based for loops, and C++17 or C++20 features where the codebase uses them.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
