Learning Resources
Top 100 Interview Q&A
The Top 100 C++ interview questions and answers, covering every major area of the language — from basics and OOP to smart pointers, modern C++, templates, exceptions, and the STL.
C++ Interview Questions & Answers
The most frequently asked C++ interview questions, covering every major area of the language — basics and modern features, OOP, inheritance and polymorphism, memory and smart pointers, move semantics and lambdas, templates and exceptions, and the STL (containers, iterators, algorithms, adapters). Each answer is written the way you should say it in an interview.
C++ Basics & Language
Q1–Q10Q1 What is C++ and how does it differ from C?
Answer C++ is a multi-paradigm language that extends C with classes, templates, references, exceptions, operator overloading, and the Standard Library (STL). It still supports procedural style and low-level control, but encourages type safety, RAII, and abstraction for large systems.
Q2 What are the main features of C++?
Answer Object-oriented programming, strong static typing, templates and generic programming, the STL, exceptions, references, operator overloading, namespaces, function and operator overloading, and modern features such as move semantics, lambdas, smart pointers, and constexpr.
Q3 What is the structure of a C++ program?
Answer Typically: includes and namespaces, optional global declarations, one main() as the entry point, and user-defined functions or classes. Execution starts at main(). Prefer using namespace std carefully or use std:: prefixes for clarity in larger code.
Q4 What is a namespace and why is it used?
Answer A namespace is a named scope that groups identifiers to avoid name collisions. The standard library lives in std. You can nest namespaces, use aliases, and bring names in with using — sparingly at file scope.
Q5 Declaration vs definition in C++?
Answer A declaration introduces a name and type without allocating storage or providing a body (e.g. class forward declaration, function prototype, extern). A definition allocates storage or provides the implementation. The One Definition Rule (ODR) requires a single definition across the program for most entities.
Q6 What is the difference between #include "" and #include <>?
Answer Angle brackets search system/standard include paths first; quotes typically search the current directory then the include path. Use <> for standard headers like <iostream> and "" for your own headers.
Q7 What is nullptr?
Answer nullptr (C++11) is a typed null pointer constant of type std::nullptr_t. Prefer it over NULL or 0 because it does not convert to integer types and avoids overload-resolution surprises.
Q8 Reference vs pointer?
Answer A reference is an alias that must be bound at initialisation and cannot be reseated or null (in normal use). A pointer stores an address, can be null, and can be reseated. Prefer references for mandatory aliases; pointers when optionality or reseating is needed.
Q9 const correctness — why does it matter?
Answer Marking objects and member functions const documents and enforces read-only intent, enables safer APIs, and allows const objects to call those methods. Interviewers expect const T& for large read-only parameters.
Q10 What is constexpr?
Answer constexpr marks variables or functions that can be evaluated at compile time when arguments allow. It enables compile-time computation, stronger constants than const alone, and clearer intent for fixed values.
OOP — Classes & Objects
Q11–Q24Q11 What is a class in C++?
Answer A user-defined type that bundles data members and member functions. It defines the shape and behaviour of objects created from it.
Q12 struct vs class?
Answer In C++ they are almost the same. Default member access and inheritance are public for struct and private for class. Conventionally use struct for simple aggregates and class for encapsulated types with invariants.
Q13 What is encapsulation?
Answer Hiding internal representation behind a controlled public interface using private/protected members so clients depend on behaviour, not layout. It protects invariants and eases refactoring.
Q14 What is abstraction?
Answer Exposing essential operations while hiding implementation details — often via interfaces (abstract base classes) or well-designed public APIs.
Q15 What are access specifiers?
Answer public is visible to all, protected to the class and derived classes, private only to the class (and friends). They enforce encapsulation.
Q16 What is a constructor? Destructor?
Answer A constructor initialises an object when it is created. A destructor cleans up when the object’s lifetime ends. Together they support RAII — bind resource lifetime to object lifetime.
Q17 What is a copy constructor and copy assignment?
Answer The copy constructor creates a new object from an existing one (T(const T&)). Copy assignment assigns from one existing object to another (T& operator=(const T&)). Both must respect ownership if the class manages resources.
Q18 What is the Rule of Three / Five / Zero?
Answer Rule of Three: if you need a custom destructor, copy constructor, or copy assignment, you likely need all three. Rule of Five adds move constructor and move assignment. Rule of Zero: prefer types that manage no raw resources so the compiler defaults suffice (use smart pointers/containers).
Q19 What does = default and = delete mean?
Answer = default asks the compiler to generate the special member. = delete forbids using it (e.g. disable copying). Useful for unique-ownership types.
Q20 What is this?
Answer Inside a non-static member function, this is a pointer to the current object. It is used to disambiguate members, return *this for chaining, and in some designs for callbacks.
Q21 What is a friend function or friend class?
Answer friend grants access to private/protected members without being a member. Friendship is not inherited or transitive. Use sparingly — it weakens encapsulation.
Q22 What is object slicing?
Answer Assigning or passing a derived object by value into a base object copies only the base subobject and drops derived data/behaviour. Prefer pointers or references for polymorphic use.
Q23 explicit constructors — why?
Answer explicit prevents unintended implicit conversions from a single argument (or conversion operators). Prefer explicit for single-argument constructors that are not meant as conversions.
Q24 What is a static member?
Answer A static data member is shared by all instances; a static member function has no this and can only access static members. Useful for counters, factories, and utilities tied to the type.
Inheritance & Polymorphism
Q25–Q36Q25 What is inheritance?
Answer Defining a derived class that reuses and extends a base class — modelling an “is-a” relationship. Prefer public inheritance for interface reuse; prefer composition for “has-a”.
Q26 Types of inheritance in C++?
Answer Single, multilevel, hierarchical, multiple, and hybrid. Multiple inheritance can introduce the diamond problem, usually solved with virtual inheritance.
Q27 What is polymorphism?
Answer “Many forms”: the same interface with different behaviour. Compile-time: overloading and templates. Runtime: virtual functions via base pointers/references.
Q28 What is a virtual function?
Answer A member function declared virtual so calls through a base pointer/reference dispatch to the most-derived override at runtime (vtable/vptr mechanism).
Q29 Why a virtual destructor?
Answer If you delete a derived object through a base pointer, a non-virtual base destructor leaves undefined behaviour / incomplete cleanup. Make the base destructor virtual when the class is used polymorphically.
Q30 What is a pure virtual function?
Answer virtual void f() = 0; makes the class abstract — you cannot instantiate it. Derived classes must override pure virtuals (unless they remain abstract).
Q31 override and final?
Answer override ensures a function actually overrides a virtual base method (catches signature mistakes). final prevents further overriding of a virtual, or further inheritance from a class.
Q32 Function overloading vs overriding?
Answer Overloading: same name, different parameter lists, resolved at compile time in one scope. Overriding: redefining a virtual function in a derived class for runtime dispatch.
Q33 What is the diamond problem?
Answer Two paths inherit the same base, causing duplicate base subobjects and ambiguity. Virtual inheritance shares a single virtual base subobject.
Q34 Early binding vs late binding?
Answer Early (static) binding resolves at compile time (non-virtual calls, overloads). Late (dynamic) binding resolves at runtime for virtual calls through base pointers/references.
Q35 Composition vs inheritance?
Answer Composition (“has-a”) embeds or owns another object and is usually more flexible. Inheritance (“is-a”) couples types; use it when you need substitutability and polymorphism.
Q36 Can constructors be virtual?
Answer No. Constructors cannot be virtual. Destructors can and often should be when used as polymorphic bases. You can use factory patterns / virtual clone idioms instead.
Memory, Pointers & Smart Pointers
Q37–Q46Q37 new/delete vs malloc/free?
Answer new/delete are typed, call constructors/destructors, and can be overloaded. malloc/free are C, work with raw bytes, and do not run constructors/destructors. Do not mix new with free or malloc with delete.
Q38 delete vs delete[]?
Answer delete pairs with new; delete[] pairs with new[]. Mismatch is undefined behaviour — wrong destructor count and heap corruption risk.
Q39 What is RAII?
Answer Resource Acquisition Is Initialization: acquire resources in constructors and release them in destructors so stack unwinding and scope exit free resources automatically (files, locks, memory).
Q40 unique_ptr vs shared_ptr vs weak_ptr?
Answer unique_ptr: exclusive ownership, movable, default choice. shared_ptr: shared ownership with reference counting. weak_ptr: non-owning observer of a shared_ptr that breaks cycles and does not keep the object alive alone.
Q41 Why prefer smart pointers over raw new?
Answer They encode ownership, prevent most leaks via RAII, and make APIs clearer. Raw owning pointers are easy to leak on early returns and exceptions.
Q42 What does std::move do?
Answer It casts to an rvalue reference so move constructors/assignments can steal resources. It does not move by itself; the overload that accepts T&& does.
Q43 What is a moved-from object?
Answer Valid but unspecified state — you may destroy or assign to it, but should not assume prior contents. Avoid using values after std::move unless documented otherwise.
Q44 Stack vs free store (heap) in C++?
Answer Automatic storage (stack) for locals with automatic lifetime. Free store for new/smart-pointer allocations with dynamic lifetime. Confusing “STL heap algorithms” with heap memory is a common interview trap.
Q45 What is a dangling pointer / reference?
Answer Referring to an object whose lifetime has ended (freed memory, destroyed temporary, out-of-scope local). Using it is undefined behaviour.
Q46 make_shared / make_unique benefits?
Answer Exception-safe creation, clearer code, and for make_shared often a single allocation for control block + object. Prefer them over raw new when constructing smart pointers.
Modern C++ — Move, Lambda, Casts
Q47–Q56Q47 What is move semantics?
Answer Transferring resources from temporaries or explicitly moved objects instead of deep-copying, improving performance for containers and resource-owning types.
Q48 lvalue vs rvalue?
Answer Roughly: lvalues have identity and persist; rvalues are temporaries or values about to expire. Rvalue references (T&&) enable move overloads.
Q49 What is a lambda expression?
Answer An anonymous function object. Capture [=] by value, [&] by reference, or list captures explicitly. Often passed to STL algorithms. Watch lifetime when capturing by reference.
Q50 std::function — what is it?
Answer A type-erased wrapper that can hold callables (functions, lambdas, bind expressions) with a given signature. Convenient but may allocate — prefer templates when possible.
Q51 static_cast vs dynamic_cast vs const_cast vs reinterpret_cast?
Answer static_cast: related conversions at compile time. dynamic_cast: safe downcast for polymorphic types (returns nullptr / throws for references on failure). const_cast: add/remove const/volatile. reinterpret_cast: low-level bit reinterpretation — use rarely.
Q52 enum vs enum class?
Answer Classic enum exports enumerators into the enclosing scope and converts to int. enum class is scoped and does not implicitly convert to int — safer.
Q53 What is auto and when to use it?
Answer auto deduces type from the initialiser. Use for long iterator types and clarity when the type is obvious; avoid when the deduced type would obscure intent.
Q54 What is a range-based for loop?
Answer for (auto& x : container) iterates via begin/end. Prefer auto& or const auto& to avoid copies of heavy elements.
Q55 What is noexcept?
Answer Declares a function does not throw. Enables optimisations (e.g. move_if_noexcept in containers) and documents contracts. Throwing from noexcept calls std::terminate.
Q56 initializer_list purpose?
Answer Enables brace initialisation like vector<int> v{1,2,3}; and uniform initialisation patterns for constructors that accept std::initializer_list.
Templates, Exceptions & Misc
Q57–Q66Q57 What are templates?
Answer Compile-time generic code parameterised by types or values. They enable the STL and zero-overhead abstraction. Instantiated per used argument list.
Q58 Function template vs class template?
Answer Function templates generate functions; class templates generate classes/structs. Both can be specialised. Member function templates cannot be virtual.
Q59 What is template specialisation?
Answer Providing a custom implementation for specific template arguments (full or partial for class templates). Used to optimise or handle special cases.
Q60 What is SFINAE?
Answer Substitution Failure Is Not An Error: invalid template substitutions are discarded during overload resolution rather than hard-erroring, enabling technique-based overload selection (historically; concepts improve this in C++20).
Q61 How do exceptions work?
Answer throw transfers control to a matching catch. Stack unwinding destroys automatic objects (RAII). Prefer catch by const reference to avoid slicing. Use exceptions for exceptional failures, not normal control flow.
Q62 What should you not throw?
Answer Avoid throwing from destructors during unwinding (risk of terminate). Prefer strong exception guarantees where practical. Document what APIs throw.
Q63 try / catch / throw basics?
Answer Code that may fail throws an exception object; handlers catch by type. A catch(...) handles any exception but should usually rethrow or log carefully.
Q64 What is a concept (C++20)?
Answer A compile-time predicate constraining template parameters, giving clearer errors and documenting requirements (e.g. sortable ranges).
Q65 Header guards / #pragma once?
Answer Prevent multiple inclusion of the same header. Classic pattern is #ifndef/#define/#endif; #pragma once is widely supported.
Q66 What is ODR?
Answer One Definition Rule: entities must have exactly one definition in the program (with careful exceptions for inline/templates). Violations cause link errors or subtle UB.
STL Containers
Q67–Q79Q67 What is the STL?
Answer The Standard Template Library portion of the C++ standard library: containers, iterators, algorithms, function objects, and adapters — designed to work together.
Q68 vector — when do you use it?
Answer Default dynamic array: contiguous storage, O(1) random access, amortised O(1) push_back. Prefer it unless you need specialised structure properties.
Q69 vector vs deque vs list?
Answer vector: contiguous, best cache locality, expensive mid inserts. deque: efficient insert/erase at both ends, not strictly one contiguous block. list: doubly linked, O(1) insert/erase given position, no random access.
Q70 map vs unordered_map?
Answer map: ordered keys (tree), O(log n), sorted iteration. unordered_map: hash table, average O(1), no order. Choose by need for order vs raw speed.
Q71 set vs multiset vs unordered_set?
Answer set: unique sorted keys. multiset: sorted keys allowing duplicates. unordered_set: unique hashed keys for fast membership.
Q72 map vs set?
Answer set stores keys only; map stores key→value pairs. If you only need membership, prefer a set/unordered_set.
Q73 What does map operator[] do if the key is missing?
Answer It default-inserts a value-initialised mapped type and returns a reference. Use find or at when insertion is unwanted; at throws if missing.
Q74 Why no operator[] on multimap?
Answer A key can map to multiple values, so a single reference would be ambiguous. Use insert and equal_range.
Q75 stack, queue, priority_queue — what are they?
Answer Container adapters with restricted interfaces. stack = LIFO, queue = FIFO, priority_queue = heap-based best-first (default max-heap).
Q76 priority_queue default order?
Answer Max-heap: largest element on top. For a min-heap use greater<> as the comparator (with the underlying container type).
Q77 When prefer unordered_map for counting?
Answer Frequency counting and dictionaries when order does not matter — average O(1) updates with m[key]++.
Q78 What invalidates vector iterators?
Answer Reallocation on growth, and insert/erase at or before an iterator typically invalidate that position and beyond. Capacity changes are the common surprise.
Q79 pair and tuple?
Answer pair holds two values; tuple holds a fixed-size heterogeneous collection. Often used as map elements and algorithm return groups.
STL Algorithms, Iterators & Heaps
Q80–Q100Q80 What are iterators?
Answer Generalised pointers into container ranges. Algorithms take iterator pairs [first, last). Categories: input, output, forward, bidirectional, random access.
Q81 How do you sort a vector?
Answer std::sort(v.begin(), v.end()); optionally with a comparator or lambda. Needs random-access iterators. Use stable_sort when equal-element order must be preserved.
Q82 find vs binary_search / lower_bound?
Answer find is linear on unsorted ranges. binary_search / lower_bound / upper_bound require sorted ranges and are logarithmic.
Q83 What is a functor?
Answer A class object with operator() that can be passed like a function — stateful callables used heavily with older STL code; lambdas largely replace them in modern C++.
Q84 make_heap / push_heap / pop_heap?
Answer Heap algorithms rearrange a random-access range into a priority heap (default max-heap). push_heap after push_back; pop_heap then pop_back to remove the top. priority_queue wraps this pattern.
Q85 STL heap vs heap memory?
Answer Different meanings. STL heap algorithms build a priority structure on a vector. Heap memory means dynamic free-store allocation.
Q86 What is back_inserter?
Answer An insert iterator that calls push_back, useful with copy/transform into an empty vector without pre-sizing.
Q87 remove vs erase idiom?
Answer std::remove shifts kept elements forward but does not shrink the container; follow with erase on the returned end (erase-remove idiom).
Q88 for_each vs range-based for?
Answer for_each applies a callable to each element; range-based for is usually clearer for simple loops. Prefer algorithms when composing with other STL pieces.
Q89 min_element / max_element?
Answer Return iterators to the smallest/largest element in a range (linear scan). Useful when you need the position, not only the value.
Q90 Interview tip for STL complexity?
Answer Know push_back amortised O(1), vector random access O(1), map find O(log n), unordered_map average O(1), and that unordered_map can rehash.
Q91 How should you prepare for a C++ interview?
Answer Be fluent in OOP + virtuals, RAII/smart pointers, value categories/move, and core STL (vector/map/unordered_map + sort/find + lambdas), plus one project you can explain end-to-end.
Q92 What is std::optional?
Answer A value that may or may not be present. Safer than sentinel values or raw pointers for “maybe a result”. Check has_value() or use value_or.
Q93 What is string_view and what is the danger?
Answer A non-owning view over character data. Fast for read-only APIs, but must not outlive the underlying string/array — dangling views are a common bug.
Q94 forward_list vs list?
Answer forward_list is singly linked (smaller nodes, forward-only). list is doubly linked (bidirectional). Prefer vector unless you truly need linked-list insert/erase properties.
Q95 What is ADL (Argument-Dependent Lookup)?
Answer When calling an unqualified function, associated namespaces of argument types are also searched — why begin/end and swap often work for user types in std algorithms.
Q96 shallow copy vs deep copy?
Answer Shallow copy duplicates pointers only; both objects share the same resource (double-free risk). Deep copy duplicates the owned resource. Critical whenever a class owns heap memory.
Q97 What is mutable?
Answer Allows a data member to be modified inside a const member function — typically for caches or lazy memoisation that do not change the logical object state.
Q98 Can you overload && or ||?
Answer Technically yes, but overloaded operator&& / || lose short-circuit evaluation. Prefer not to overload them.
Q99 What is PIMPL?
Answer Pointer to Implementation: hide private details behind an opaque pointer in the header to reduce compile-time coupling and ABI churn.
Q100 Undefined behaviour examples in C++?
Answer Out-of-bounds access, use-after-free, double delete, signed integer overflow, data races, and deleting derived objects through non-virtual base destructors.