C++ Interview Questions and Answers
Last updated 2026-11-19
This page collects the C++ questions that come up across campus tests and technical rounds: language basics, value categories, move semantics, const correctness, undefined behaviour and the modern features of C++17 and C++20. Every answer is written the way you would say it aloud, with the reason behind the rule and the trap an interviewer is usually hunting for.
C++ interviews reward precision. "A reference is an alias" is fine as a starting line, but the follow-up is always about lifetime, binding rules or what the compiler actually generates. Work through the questions below, run the snippets yourself, and keep the standard version in mind: everything here is valid C++17 unless the answer says C++20.
For the sub-topics that deserve their own page, see C++ OOPS questions, C++ STL questions and C++ smart pointers.
| Standard | C++17 unless stated, C++20 where noted |
|---|---|
| Style | Short worked answers with code |
| Best for | Campus tests and technical rounds |
What interviewers actually probe in C++
Most C++ questions are really about ownership and lifetime: who frees this, when does this object die, does this copy or move. If you can answer those three for any snippet, you can answer most of the paper.
The second theme is undefined behaviour. Signed overflow, out-of-range access, dangling references and reading uninitialised locals are not "bugs that crash", they are permission for the compiler to do anything. Say that sentence clearly and you stand out.
- Know the rule of zero, three and five and when each applies.
- Know what const on a member function promises and what mutable relaxes.
- Be able to say what lvalue, prvalue and xvalue mean without drawing a table.
- Prefer standard containers and smart pointers in every code answer you write.
How to practise
Compile every snippet with -Wall -Wextra and, where possible, with -fsanitize=address,undefined. Many output-prediction questions stop being mysterious once a sanitizer names the exact line. For the numbers and coding-round side of preparation, see how to crack a DSA coding round.
C++ Interview Questions and Answers: questions with worked answers
1 What is the difference between a pointer and a reference in C++?
easyA reference is an alias bound once at initialisation to an existing object. It cannot be reseated, cannot be null in well-formed code and needs no dereference syntax. A pointer is an object holding an address: it can be null, reassigned, incremented and can point to nothing. Use references for parameters that must refer to something and pointers when absence or reseating is meaningful. A reference to a member of a destroyed object dangles exactly as a pointer would.
2 What does const do in "const int* p", "int* const p" and "const int* const p"?
easyRead the declaration right to left. const int* p is a pointer to a const int: you cannot modify *p but you can repoint p. int* const p is a const pointer to int: you can modify *p but cannot repoint p. const int* const p forbids both. Top-level const on a by-value parameter does not change the function signature, but low-level const (pointee) does, so f(int*) and f(const int*) are distinct overloads.
cppint x = 1, y = 2; const int* a = &x; // *a = 5; error, a = &y; ok int* const b = &x; // *b = 5; ok, b = &y; error const int* const d = &x; // both error3 Explain RAII and why it matters for exception safety.
mediumRAII ties a resource to an object lifetime: acquire in the constructor, release in the destructor. Because destructors of fully constructed automatic objects run during stack unwinding, the resource is released on every exit path, including exceptions and early returns. std::vector, std::string, std::unique_ptr, std::lock_guard and std::fstream are all RAII types. The interview follow-up is that a destructor must not throw, since a throw during unwinding calls std::terminate.
cpp#include <mutex> std::mutex m; void work() { std::lock_guard<std::mutex> g(m); // locked might_throw(); // unlocks even if this throws }4 What is the rule of zero, three and five?
mediumRule of three: if you define a destructor, copy constructor or copy assignment, you almost certainly need all three, because you are managing a resource by hand. Rule of five adds the move constructor and move assignment for efficiency. Rule of zero is the preferred modern style: hold resources in members that manage themselves (vector, string, unique_ptr) and declare none of the five, so the compiler-generated versions are correct. Declaring a destructor suppresses the implicit move operations, so copies silently replace moves, a classic performance gotcha.
5 What is the difference between lvalue, prvalue and xvalue?
mediumAn lvalue has identity and a stable address (a named variable). A prvalue is a pure temporary value with no identity, such as 42 or a function returning by value. An xvalue is an "expiring" object with identity that may be moved from, such as the result of std::move(x). A glvalue is an lvalue or xvalue; an rvalue is a prvalue or xvalue. An rvalue reference T&& binds to rvalues, which is what lets move constructors steal resources. Since C++17, guaranteed copy elision means a prvalue initialises its target directly, with no temporary and no move.
6 What does std::move actually do?
mediumNothing at run time. std::move is an unconditional cast to an rvalue reference (static_cast<T&&>). The move happens only when something then selects a move constructor or move assignment. Moving from an object leaves it valid but unspecified, so you may only assign to it or destroy it. Returning a local with return std::move(x) is usually a mistake: it blocks copy elision (NRVO) and forces a move where none was needed.
cppstd::string a = "hello"; std::string b = std::move(a); // b owns the buffer // a is valid but unspecified: do not read its value a = "reuse"; // fine7 What is the difference between new/delete and malloc/free?
mediumnew calls operator new to get memory and then runs the constructor; delete runs the destructor and then frees. malloc/free only deal with raw bytes and never call constructors or destructors. new throws std::bad_alloc on failure (unless you use nothrow) while malloc returns NULL. new returns a correctly typed pointer; malloc returns void*. Never mix them: memory from new[] must be released with delete[], from new with delete, from malloc with free. Mixing is undefined behaviour. In modern code prefer make_unique and containers over any of them.
8 What is undefined behaviour? Give three examples and say why it is dangerous.
mediumThe standard places no requirements on the program, so the compiler may assume it never happens and optimise accordingly. Examples: signed integer overflow (INT_MAX + 1), accessing an array out of bounds or a dangling pointer, and reading an uninitialised local. The danger is that the symptom is unrelated to the cause: an overflow check written as "if (x + 1 < x)" can be deleted entirely because the compiler assumes signed overflow is impossible. Unsigned overflow is defined (wraps modulo 2^N), which is a frequent follow-up.
9 Predict the output.
mediumIt prints 3 3 4. Each statement here is separate, so it is well defined: i++ yields the old value 3 and then i becomes 4. Contrast it with something like i = i++ + ++i, which modifies i twice without sequencing and is a trap where a good answer says undefined or unspecified. The point is the difference between post-increment (returns a copy of the old value) and pre-increment (returns the incremented object).
cppint i = 3; int a = i; // 3 int b = i++; // b = 3, i = 4 int d = i; // 4 std::cout << a << " " << b << " " << d; // 3 3 410 What is the difference between std::vector push_back and emplace_back?
hardpush_back takes an already-constructed object (copying or moving it in), while emplace_back forwards its arguments and constructs the element in place inside the vector storage. For a type like std::pair<int,std::string>, emplace_back(1, "x") avoids a temporary. The gain over push_back with a braced temporary is often small because push_back(T&&) also moves. The gotcha: emplace_back can call explicit constructors and can hide a conversion you did not intend. Both may reallocate, invalidating all iterators, pointers and references into the vector.
11 What are the C++ casts and when would you use each?
mediumstatic_cast does checked-at-compile-time conversions such as int to double or base to derived pointer when you know the type. dynamic_cast performs a run-time checked downcast on polymorphic types and returns nullptr (pointer) or throws std::bad_cast (reference) on failure. const_cast adds or removes const and is only safe if the object was not originally const. reinterpret_cast reinterprets bit patterns between unrelated pointer types and is the most dangerous. The C-style cast tries all of them and hides which one it chose, so avoid it.
12 How do lambdas capture variables, and what is the dangling-capture trap?
mediumA lambda is an anonymous class with an operator(). [=] copies used variables, [&] stores references, [x] copies x and [&x] references x. C++14 adds init-capture such as [p = std::move(ptr)], which is the way to move a unique_ptr into a lambda. The trap is capturing by reference something that dies before the lambda is called, for example returning a lambda that captures a local by [&]. Copies are const inside the lambda unless it is declared mutable.
cppauto make() { int n = 5; return [&] { return n; }; // dangling: n is gone when called } auto make_ok() { int n = 5; return [n] { return n; }; // copy, safe }13 What does the static keyword mean in different contexts?
mediumAt namespace scope, static gives a name internal linkage, so it is private to the translation unit. Inside a function, a static local is initialised once, on first call, and lives for the whole program; since C++11 that initialisation is thread-safe. Inside a class, a static data member is shared by all objects and (before C++17 inline variables) needed an out-of-class definition; a static member function has no this pointer and cannot touch non-static members. Static locals are why singletons written as "static T inst;" are safe from races on construction.
14 Why is a base-class destructor usually virtual?
hardDeleting a derived object through a base pointer is undefined behaviour unless the base destructor is virtual, because only the base destructor would run and derived members would leak. Making it virtual dispatches the delete to the most derived destructor first, then the base. A class meant as a polymorphic base should therefore have either a public virtual destructor or a protected non-virtual one. See C++ virtual functions for vtable detail.
15 What is the difference between struct and class in C++?
mediumOnly the defaults: members and base-class inheritance are public in a struct and private in a class. Both can have constructors, member functions, inheritance and virtual functions. By convention struct is used for passive data aggregates and class when there are invariants to protect. An aggregate (no user-provided constructors, no private members, no virtual functions) can be initialised with braces, and in C++20 even with designated initialisers like Point{.x = 1, .y = 2}.
16 What does the following print, and why?
hardOn a typical 64-bit platform it prints 40 and then 8. sizeof gives the size of the whole array in main, but a function parameter written as int a[10] is really an int*, so inside f the sizeof is the pointer size. The exact numbers depend on the platform: sizeof(int) is 4 and a pointer is 8 there. The lesson is array-to-pointer decay: an array loses its size when passed by value, so pass std::array, std::span (C++20) or a reference to the array.
cppvoid f(int a[10]) { std::cout << sizeof(a) << "\n"; } // 8 on 64-bit int main() { int a[10]; std::cout << sizeof(a) << "\n"; // 40 f(a); }17 What are C++17 features you would mention in an interview?
mediumStructured bindings (auto [k, v] = *it), if and switch with initialisers, std::optional, std::variant and std::visit, std::string_view, fold expressions, inline variables, guaranteed copy elision and class template argument deduction. In C++20 the headline items are concepts, ranges, coroutines, three-way comparison (<=>), std::span and modules. Pick two or three you have used and explain the problem each solves, rather than reciting a list.
Frequently asked questions
Which C++ standard should I study for interviews?
Know C++11 thoroughly (move semantics, auto, lambdas, smart pointers), then add C++17 and C++20 highlights such as structured bindings, optional, concepts and ranges. Most interviews do not go beyond that.
Are C++ questions asked in non-C++ roles?
Yes. Many service and product companies ask C++ basics, pointers and OOP even when the role is general, because it tests memory understanding. Check the job description for the language list.
How do I prepare for output-prediction questions?
Compile and run them with warnings and sanitizers on, and always ask whether the snippet is defined, unspecified or undefined behaviour before predicting. See C programming output questions for more practice.
Is STL knowledge enough for coding rounds?
It covers most DSA problems, but you should still be able to explain iterator invalidation, complexity guarantees and when to write your own structure. See C++ STL questions.
Related guides
More in Programming Language Interview Questions by Language
- C++ Memory Management Interview Questions
- C++ OOPS Interview Questions
- C++ Pointers and References Interview Questions
- C++ Smart Pointers Interview Questions
- C++ STL Interview Questions
- C++ Templates Interview Questions
- C++ Virtual Functions Interview Questions
- Core Java Interview Questions for Freshers
- Entity Framework Core Interview Questions
- Java 8 Streams and Lambdas Interview Questions
- Java Coding Interview Questions
- Java Collections Interview Questions