C++ is asked in interviews for product companies, game development, embedded systems, finance and competitive programming. These C++ interview questions cover OOP, references and constructors for freshers, then virtual functions, memory management, smart pointers, move semantics, templates, the STL and modern C++ for experienced developers.
30 questions · Updated
Reading answers is not the same as saying them.Practise C++ questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AIC++ Interview Questions: 30 questions with model answers on this page.
Basic C++ interview questions
Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.
1. What is the difference between C and C++?
Answer flow · 3 steps
1
C is a procedural language.
2
C++ adds object-oriented programming with classes, inheritance and polymorphism, plus references, function and operator overloading, templates, exceptions, namespaces and the Standard Template Library.
3
C++ is mostly compatible with C, but adds features for building large, abstract and type-safe programs.
2. What is the difference between a pointer and a reference?
Answer flow · 3 steps
1
A pointer stores an address, can be null, can be reassigned to point elsewhere and needs * to access the value.
2
A reference is an alias for an existing variable, must be initialised when declared, cannot be null or reseated, and is used like the variable itself.
3
References are preferred for function parameters when null is not a valid value.
3. What are constructors and destructors?
A constructor is a special member function that initialises an object when it is created; it has the class name and no return type, and can be default, parameterised or a copy constructor. A destructor, named ~ClassName, runs automatically when the object goes out of scope or is deleted, and releases resources such as memory, files or locks.
4. What is the difference between a class and a struct in C++?
Answer flow · 3 steps
1
They are almost identical: both can have data, functions, constructors, inheritance and access specifiers.
2
The only difference is the default: struct members and base classes are public by default, while class members and base classes are private by default.
3
By convention, struct is used for simple data aggregates and class for types with invariants and behaviour.
5. What are access specifiers and friend functions?
public members are accessible from anywhere, protected members from the class and its derived classes, and private members only within the class. A friend function or friend class declared inside a class can access its private members, which is used sparingly, for example to implement operator<< for printing an object.
6. What are function overloading and default arguments?
Answer flow · 3 steps
1
Function overloading allows several functions with the same name but different parameter types or numbers, and the compiler picks the best match at compile time.
2
Default arguments give parameters default values, such as void connect(std::string host, int port = 443), so callers can omit them.
3
Defaults must be at the end of the parameter list.
7. What is operator overloading?
Answer flow · 3 steps
1
Operator overloading lets user-defined types work with operators, such as adding two Vector objects with + or comparing them with ==.
2
It is defined as a member or non-member function named operator+.
3
Overloads should behave as users expect; operators such as ::, ., .* and ?: cannot be overloaded, and C++20 can generate comparison operators with operator<=>.
8. What is the difference between new/delete and malloc/free?
new allocates memory and calls the constructor, returns a typed pointer and throws std::bad_alloc on failure; delete calls the destructor and frees memory (new[] must be paired with delete[]). malloc and free only allocate and release raw memory without constructors or destructors. In modern C++, smart pointers and containers should manage memory instead of manual new and delete.
9. What are namespaces?
Namespaces group names to avoid conflicts between libraries, such as std::vector and a project's own vector type. You refer to names with the scope operator (std::cout) or bring them in with using declarations. using namespace std; in header files is bad practice because it pollutes every file that includes the header.
10. What are inline functions?
Answer flow · 3 steps
1
inline suggests the compiler replace a function call with the function's body to avoid call overhead, but modern compilers decide inlining themselves.
2
Today the main meaning of inline is that a function or variable may be defined in a header included by several files without violating the one-definition rule.
3
Functions defined inside a class body are implicitly inline.
11. What is const correctness?
Const correctness means marking everything that should not change as const: const variables, const references for parameters that are not modified (const std::string&), and const member functions, which promise not to change the object and can be called on const objects. It documents intent, prevents accidental changes and enables compiler optimisations.
Intermediate C++ interview questions
Applied problems, trade-offs and questions about your own projects.
12. What are virtual functions, and how does runtime polymorphism work?
Answer flow · 3 steps
1
A virtual function in a base class can be overridden in derived classes, and calls through a base pointer or reference run the derived version based on the actual object type.
2
This is implemented with a vtable, a table of function pointers for each class, and a vptr in each object.
3
A base class with virtual functions should have a virtual destructor so derived objects are destroyed correctly.
13. What is RAII?
Answer flow · 3 steps
1
Resource Acquisition Is Initialisation means tying a resource's lifetime to an object: the constructor acquires the resource and the destructor releases it.
2
Because destructors run automatically when objects go out of scope, even when exceptions are thrown, resources are never leaked.
3
Smart pointers, std::lock_guard and file streams all use RAII.
14. What are smart pointers?
Smart pointers manage dynamically allocated memory automatically. std::unique_ptr has sole ownership and frees the object when it goes out of scope; it can be moved but not copied. std::shared_ptr shares ownership with reference counting, freeing the object when the last owner is gone. std::weak_ptr observes a shared_ptr without owning it, breaking reference cycles. make_unique and make_shared create them safely.
15. Which STL containers do you use, and when?
vector is the default dynamic array with fast random access. deque allows fast insertion at both ends. list is a doubly linked list for frequent insertions in the middle. map and set are sorted red-black trees with O(log n) operations, while unordered_map and unordered_set are hash tables with average O(1). stack, queue and priority_queue are adapters on top of these.
16. How does virtual inheritance solve the diamond problem?
If B and C both inherit from A, and D inherits from both B and C, D normally contains two copies of A, making access to A's members ambiguous. Declaring B and C with virtual public A makes them share a single A subobject in D. The most derived class is then responsible for constructing A.
17. What are pure virtual functions and abstract classes?
Answer flow · 3 steps
1
A pure virtual function is declared with = 0, such as virtual double area() const = 0;, and has no implementation in the base class.
2
A class with at least one pure virtual function is abstract and cannot be instantiated; derived classes must override the function to become concrete.
3
Abstract classes act as interfaces in C++.
18. What is the difference between a shallow copy and a deep copy?
Answer flow · 3 steps
1
The default copy constructor copies members one by one, so for a class holding a raw pointer, both objects end up pointing to the same memory (a shallow copy), and destroying one leaves the other with a dangling pointer and causes double deletion.
2
A deep copy allocates new memory and copies the data.
3
Using std::vector, std::string or smart pointers avoids writing this by hand.
19. What are the four C++ casts?
static_cast performs checked conversions known at compile time, such as numeric conversions and up-casts. dynamic_cast safely down-casts in polymorphic class hierarchies, returning nullptr (or throwing for references) if the object is not of the target type. const_cast adds or removes const. reinterpret_cast reinterprets bits as another type and is dangerous. C-style casts should be avoided because they hide which conversion happens.
20. How does exception handling work in C++?
Code that may fail throws an exception object, usually derived from std::exception, which is caught by a matching catch block, ideally by const reference. During stack unwinding, destructors of local objects run, which is why RAII keeps resources safe. noexcept marks functions that do not throw, which helps optimisation; destructors should never throw.
21. How do STL iterators and algorithms work together?
Answer flow · 3 steps
1
Iterators are generalised pointers that let algorithms work on any container.
2
Algorithms in <algorithm> such as sort, find, find_if, count_if, transform, accumulate, binary_search and lower_bound take iterator ranges, and C++20 ranges versions take containers directly, as in std::ranges::sort(v).
3
Using algorithms is usually clearer and less buggy than writing loops.
22. How do lambdas and captures work?
Answer flow · 3 steps
1
A lambda is an anonymous function object: [capture](parameters) { body }.
2
Captures decide which outer variables it can use: [x] by value, [&x] by reference, [=] all used variables by value, [&] all by reference, and [this] the current object.
3
Capturing by reference is dangerous if the lambda outlives the variables, for example when stored or run on another thread.
High level C++ interview questions
System design, deep internals, leadership and tough follow-ups.
23. What are move semantics?
Answer flow · 3 steps
1
Move semantics, from C++11, let resources be transferred from temporary objects instead of copied.
2
An rvalue reference (T&&) binds to temporaries, and a move constructor or move assignment operator takes over the source's resources, such as a heap buffer, and leaves it empty. std::move casts an object to an rvalue to allow moving.
3
This makes returning and storing large objects much cheaper.
24. What is the rule of three, five and zero?
Answer flow · 3 steps
1
The rule of three says that if a class needs a custom destructor, copy constructor or copy assignment operator, it probably needs all three, because it manages a resource.
2
The rule of five adds the move constructor and move assignment operator.
3
The rule of zero says the best design avoids all of them by using RAII members, such as smart pointers and standard containers, which handle copying and cleanup automatically.
25. What are templates, and what are some modern C++ features you use?
Templates let you write generic functions and classes that work with any type, resolved at compile time, as the STL does with std::vector<T>. Modern C++ features I use include auto, range-based for loops, lambdas, smart pointers, constexpr, structured bindings, std::optional and std::variant (C++17), and concepts, ranges and std::span (C++20), which make code safer and more expressive.
26. What is object slicing?
Answer flow · 3 steps
1
Object slicing happens when a derived object is copied into a base class object by value: only the base part is copied and the derived part is lost, so virtual functions behave like the base version.
2
For example, passing a Dog to a function taking an Animal by value.
3
Avoid it by passing polymorphic objects by reference or pointer.
27. How do you write multithreaded code in C++?
std::thread (or std::jthread in C++20, which joins automatically and supports stop tokens) starts threads. std::mutex with std::lock_guard or std::scoped_lock protects shared data, std::condition_variable lets threads wait for conditions, std::atomic provides lock-free operations on simple values, and std::async and std::future run tasks and collect results. Data races are undefined behaviour.
28. How do you find undefined behaviour and memory bugs in C++?
Compile with warnings (-Wall -Wextra) and treat them as errors, run tests with sanitisers (AddressSanitizer for out-of-bounds and use-after-free, UndefinedBehaviorSanitizer, ThreadSanitizer for data races, MemorySanitizer for uninitialised reads), use Valgrind, run static analysers such as clang-tidy, and prefer safe abstractions such as containers, smart pointers, std::span and bounds-checked access.
29. What is CRTP?
Answer flow · 3 steps
1
The Curiously Recurring Template Pattern is when a class derives from a template instantiated with itself: class Derived : public Base<Derived>.
2
The base class can call derived methods through static_cast<Derived*>(this) at compile time, giving polymorphism without virtual function overhead (static polymorphism).
3
It is used for mixins, counters and performance-critical libraries.
30. How do you write fast, cache-friendly C++?
Measure first with a profiler. Keep data contiguous (std::vector instead of std::list or maps of pointers), access memory sequentially, use structures of arrays for hot loops, avoid unnecessary copies with references and move semantics, reserve capacity for vectors, reduce heap allocations, avoid virtual calls in tight loops, and let the compiler optimise with -O2 or -O3 and link-time optimisation.
Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.