C++ Programming Interview Questions

50 questions and answers covering C++ Programming, from fundamentals through practical, debugging, and design-level topics.

50 of 50 interview questions

  1. At a high level, what does C++ add on top of plain C?beginnerC++ Fundamentals: What C++ Adds Over C

    Object-oriented features (classes, inheritance, polymorphism), references, function/operator overloading, templates for generic programming, RAII-based resource management, exceptions, and the Standard Template Library -- while remaining largely (though not perfectly) backward-compatible with C.

  2. What is a reference in C++, and how does it differ from a pointer?intermediateC++ Fundamentals: What C++ Adds Over C

    A reference (`int &r = x;`) is an alias for an existing variable -- unlike a pointer, it must be initialized when declared, can never be reassigned to refer to something else, and can never be `null`, making it generally safer (and syntactically simpler, no `*`/`&` dereferencing needed) for cases where those constraints are acceptable.

    int x = 5;
    int &r = x;
    r = 10;  // x is now 10
  3. What does the `auto` keyword do in modern C++?intermediateC++ Fundamentals: What C++ Adds Over C

    It lets the compiler infer a variable's type from its initializer, rather than the developer writing it out explicitly -- useful for reducing verbosity, especially with complex template-derived types (like iterator types), while still keeping full static type safety since the type is determined at compile time.

    auto count = 5;         // inferred as int
    auto it = vec.begin();  // inferred as the iterator type
  4. What is function overloading, and how does the compiler decide which overload to call?intermediateC++ Fundamentals: What C++ Adds Over C

    Defining multiple functions with the same name but different parameter lists (different types, count, or order) -- the compiler resolves which specific overload to invoke at COMPILE time, based on the number and static types of the arguments in each specific call.

  5. What is operator overloading, and give an example of when it's genuinely useful (versus when it can hurt readability)?advancedC++ Fundamentals: What C++ Adds Over C

    Defining custom behavior for an operator (`+`, `==`) when applied to a user-defined type -- genuinely useful for types with a natural mathematical/comparison meaning (like a `Vector2D` class supporting `+`); can hurt readability when overloaded in a way that doesn't match the operator's normal intuitive meaning (e.g. `+` doing something unrelated to addition).

  6. Why is C++ generally described as 'a superset of C, mostly,' rather than a strictly compatible extension?advancedC++ Fundamentals: What C++ Adds Over C

    Most valid C code compiles as valid C++, but there are real, if uncommon, differences (like C's implicit `void*` to other pointer type conversion not being allowed without a cast in C++) -- 'mostly compatible' is more accurate than 'perfectly compatible.'

  7. What does C++'s exception handling (`try`/`catch`/`throw`) let you do that plain C's error-code-return convention cannot as cleanly?advancedC++ Fundamentals: What C++ Adds Over C

    Exceptions let error handling be separated from the normal control-flow path, propagating automatically up the call stack until caught, rather than requiring every intermediate function to explicitly check and propagate an error code -- a tradeoff between control-flow clarity and the explicitness of C-style error codes, with real performance/design implications either way.

  8. What is the C++ Standard Template Library (STL), broadly?beginnerC++ Fundamentals: What C++ Adds Over C

    A collection of generic, reusable containers (vector, map, set), algorithms (sort, find), and iterators built using templates -- provides battle-tested, efficient implementations of common data structures/algorithms so developers rarely need to hand-write them from scratch.

  9. Why does C++ remain foundational for games, finance, and high-performance systems specifically, despite the availability of higher-level languages?intermediateC++ Fundamentals: What C++ Adds Over C

    It offers fine-grained control over memory and performance (comparable to C) while also providing higher-level abstractions (classes, templates, RAII) that make large, complex systems more manageable -- a combination of raw performance and structured abstraction that domains with strict latency/throughput requirements specifically value.

  10. Why might reading and predicting the output of a small C++ program (involving constructors/destructors/references) be a genuinely useful interview exercise?intermediateC++ Fundamentals: What C++ Adds Over C

    It tests whether you understand exactly WHEN constructors/destructors run (especially with temporaries, copies, and scope exits) and how references alias variables -- C++'s object lifecycle has enough subtlety that accurately tracing through code is a stronger signal of understanding than reciting definitions.

  11. What is the difference between `struct` and `class` in C++?intermediateClasses, Constructors & Encapsulation

    Functionally nearly identical -- the only real difference is the DEFAULT access level: `struct` members are `public` by default, `class` members are `private` by default. Convention typically uses `struct` for simple data-holding types and `class` for types with real encapsulated behavior/invariants.

  12. What is a constructor, and what does it guarantee about a newly-created object?beginnerClasses, Constructors & Encapsulation

    A special member function automatically called when an object is created, responsible for initializing its state -- it guarantees an object is never left in a truly uninitialized state after construction, as long as the constructor itself correctly initializes every member.

  13. What is a destructor, and when does it get called?beginnerClasses, Constructors & Encapsulation

    A special member function (`~ClassName()`) automatically called when an object's lifetime ends -- for a stack-allocated object, when it goes out of scope; for a heap-allocated object via `new`, when explicitly `delete`d (or, with a smart pointer, automatically when the last owning reference is destroyed).

  14. What is the difference between the `public`, `private`, and `protected` access specifiers?beginnerClasses, Constructors & Encapsulation

    `public` members are accessible from anywhere; `private` members are accessible only within the class itself; `protected` members are accessible within the class and by its derived (subclass) classes but not from outside -- these control encapsulation, deciding what's part of a class's exposed interface versus internal implementation.

  15. What is a copy constructor, and when is it automatically invoked?advancedClasses, Constructors & Encapsulation

    A constructor that initializes a new object as a copy of an EXISTING object of the same type -- automatically invoked when an object is passed by value, returned by value (in some cases), or explicitly copy-initialized (`ClassName b(a);` or `ClassName b = a;`).

  16. Why is the compiler-generated default copy constructor dangerous for a class that manages a raw pointer/resource internally?advancedClasses, Constructors & Encapsulation

    The default copy constructor performs a SHALLOW copy (copying the pointer value itself, not what it points to) -- two objects end up pointing at the SAME underlying resource, so when one is destroyed and frees it, the other is left with a dangling pointer, and if both are destroyed, the resource gets double-freed.

    Common mistake: Relying on the compiler-generated default copy constructor for a class managing a raw resource, causing a shallow copy and a later double-free or dangling pointer.

  17. What is member initializer list syntax (`Point(int x, int y) : x_(x), y_(y) {}`), and why is it generally preferred over assigning members inside the constructor body?advancedClasses, Constructors & Encapsulation

    It initializes members directly at construction time, rather than default-constructing them first and then reassigning inside the body -- more efficient (avoids a redundant default-construct-then-assign step) and REQUIRED for `const` members and reference members, which can't be assigned after initialization at all.

  18. What does it mean for a class to have multiple constructors (constructor overloading)?intermediateClasses, Constructors & Encapsulation

    A class can define several constructors with different parameter lists, letting objects be constructed different ways (e.g. a default constructor with no arguments, and another taking initial values) -- the compiler selects the appropriate one based on the arguments provided at the object's creation.

  19. What does declaring a member function `const` (e.g. `int getValue() const;`) mean?advancedClasses, Constructors & Encapsulation

    It promises the method will NOT modify the object's state -- lets that method be called on a `const` instance of the class (which would otherwise be forbidden), and the compiler enforces the promise by rejecting any attempt inside the method body to modify a non-`mutable` member.

  20. Why does encapsulation (keeping data `private` and exposing controlled access via methods) matter for maintaining a class's internal invariants?intermediateClasses, Constructors & Encapsulation

    If internal data is directly `public`, any external code can put the object into an inconsistent state that violates assumptions the class's own methods rely on -- encapsulation lets the class guarantee its invariants (e.g. 'balance is never negative') hold at all times, since every state change must go through methods that can enforce that rule.

  21. What does RAII (Resource Acquisition Is Initialization) mean, and what problem does it solve?advancedRAII, Smart Pointers & References vs. Pointers

    A pattern where a resource (memory, a file handle, a lock) is acquired in a constructor and automatically released in the destructor -- since C++ guarantees destructors run when an object goes out of scope (even during exception unwinding), RAII ties resource cleanup to object lifetime, making leaks far less likely than manual, error-prone acquire/release calls.

  22. What is `std::unique_ptr`, and what ownership model does it enforce?advancedRAII, Smart Pointers & References vs. Pointers

    A smart pointer representing SOLE ownership of a dynamically-allocated object -- it can't be copied (only moved), and automatically deletes the owned object when the `unique_ptr` itself is destroyed, ensuring exactly one owner and automatic cleanup with no manual `delete` needed.

    std::unique_ptr<Widget> w = std::make_unique<Widget>();
    // automatically deleted when w goes out of scope
  23. What is `std::shared_ptr`, and how does it decide when to actually delete the owned object?advancedRAII, Smart Pointers & References vs. Pointers

    A smart pointer allowing MULTIPLE owners of the same object, tracked via a reference count -- the object is automatically deleted only once the LAST owning `shared_ptr` is destroyed (reference count reaches zero), letting ownership be genuinely shared across multiple parts of a program.

  24. Why are smart pointers strongly preferred over raw `new`/`delete` in modern C++?intermediateRAII, Smart Pointers & References vs. Pointers

    Manual `new`/`delete` requires the developer to correctly match every allocation with exactly one deallocation, on every code path (including exception paths) -- easy to get wrong, leading to leaks or double-frees; smart pointers automate this via RAII, making resource management far more reliable by default.

    Common mistake: Reaching for raw new/delete in modern C++ instead of an appropriate smart pointer, reintroducing manual memory-management risk unnecessarily.

  25. What is `std::weak_ptr`, and what problem does it solve that `shared_ptr` alone cannot?advancedRAII, Smart Pointers & References vs. Pointers

    A non-owning reference to an object managed by a `shared_ptr`, which doesn't affect the reference count -- specifically solves the reference-cycle problem (two `shared_ptr`s pointing at each other, each keeping the other's reference count above zero forever, leaking both) by letting one side hold a non-owning `weak_ptr` instead.

  26. Why is `std::make_unique<T>()` generally preferred over `std::unique_ptr<T>(new T())`?advancedRAII, Smart Pointers & References vs. Pointers

    `make_unique` avoids a subtle exception-safety pitfall in some expressions where a raw `new` and its wrapping in a smart pointer aren't guaranteed to happen in a single, uninterruptible step -- it's also more concise and avoids writing the type name twice.

  27. When would you choose a reference parameter (`void process(Widget &w)`) over a pointer parameter (`void process(Widget *w)`)?advancedRAII, Smart Pointers & References vs. Pointers

    Use a reference when the parameter is guaranteed to always refer to a valid, existing object (references can't be null and can't be reassigned) -- use a pointer when the parameter might legitimately be absent (`nullptr`) or when you need to represent 'no object' as a distinct, valid state.

  28. What is the 'Rule of Three' (or its modern extension, the 'Rule of Five'), and why does it matter for a class managing a resource manually?advancedRAII, Smart Pointers & References vs. Pointers

    If a class needs a custom destructor, it almost certainly also needs a custom copy constructor and copy assignment operator (Rule of Three) -- extended to five in modern C++ to also cover move constructor and move assignment -- because the compiler's default versions of these likely do the wrong (shallow-copy) thing for a class managing a resource.

  29. What is move semantics (`std::move`), and what problem does it solve compared to always copying?advancedRAII, Smart Pointers & References vs. Pointers

    Move semantics let a resource (like a large `vector`'s internal buffer) be TRANSFERRED from one object to another, cheaply (just repointing internal pointers), instead of expensively deep-copying its entire contents -- especially valuable when a temporary/about-to-be-destroyed object's resources can simply be 'stolen' rather than copied.

  30. Why does using smart pointers and RAII generally still require SOME care, even though they eliminate most manual memory-management bugs?advancedRAII, Smart Pointers & References vs. Pointers

    Smart pointers eliminate manual new/delete mismatches, but you can still create logical errors (like a reference cycle with two `shared_ptr`s, or storing a raw pointer/reference to data whose owning smart pointer has already been destroyed) -- RAII/smart pointers reduce the RISK surface significantly but don't make correct resource management entirely automatic.

  31. What is a C++ template, and what problem does it solve?intermediateTemplates & STL

    A way to write generic code (a function or class) that works with any type, with the actual type filled in at COMPILE time -- solves the problem of needing to duplicate near-identical logic for every different type (e.g. a `max` function that works for `int`, `double`, or any comparable type) without sacrificing static type safety.

    template <typename T>
    T max(T a, T b) { return a > b ? a : b; }
  32. How does template instantiation work -- does the compiler generate separate code for each type a template is used with?advancedTemplates & STL

    Yes -- the compiler generates a distinct, fully-typed version of the template's code for each unique combination of types it's actually instantiated with, at compile time -- this is why template code errors sometimes only surface when the template is actually used with a specific type, not when the template itself is defined.

  33. What is `std::vector`, and why is it usually the default choice for a dynamic array/list in C++?intermediateTemplates & STL

    A resizable, contiguous-memory array container from the STL -- it's usually the default choice because contiguous memory gives good cache locality/performance for most access patterns, and it provides safe, well-tested resizing, indexing, and iteration compared to hand-managing a raw dynamic array.

  34. What is an iterator in the STL, and what abstraction does it provide over different container types?advancedTemplates & STL

    An object providing a uniform way to traverse a container's elements (similar in spirit to a generalized pointer) -- the same STL algorithms (`sort`, `find`) can work across very different underlying container types (vector, list, set) because they operate through this common iterator interface rather than each container's specific internal structure.

  35. What does `std::sort` from the STL algorithms library let you do, and why is it generally preferred over hand-writing a sort function?intermediateTemplates & STL

    It sorts a range (given by begin/end iterators) using a highly-optimized, well-tested implementation -- reaching for it instead of hand-writing a sort avoids re-implementing (and likely introducing bugs into) something the standard library already provides efficiently and correctly.

    std::sort(numbers.begin(), numbers.end());
  36. What is the difference between `std::vector`, `std::list`, and `std::map` in terms of their underlying structure and access patterns?advancedTemplates & STL

    `vector` is a contiguous dynamic array (fast random access, slower middle insertion); `list` is a doubly-linked list (fast insertion/removal anywhere given an iterator, slow random access); `map` is typically a balanced binary search tree keeping keys sorted (O(log n) lookup, insertion, ordered iteration).

  37. What is a lambda expression in C++, and how is it commonly used with STL algorithms?advancedTemplates & STL

    An inline, anonymous function definition (`[](int x) { return x > 0; }`) -- commonly passed directly as a predicate/comparator to STL algorithms (`std::sort`, `std::find_if`) without needing to separately define a named function elsewhere just for that one-off use.

    std::sort(items.begin(), items.end(), [](const Item &a, const Item &b) {
      return a.price < b.price;
    });
  38. What does capturing a variable by reference (`[&x]`) versus by value (`[x]`) mean in a C++ lambda?advancedTemplates & STL

    Capturing by value copies the variable's value at the time the lambda is created, unaffected by later changes to the original; capturing by reference lets the lambda see (and potentially modify) the actual original variable, reflecting whatever its value is when the lambda is eventually called.

  39. Why might overusing deeply-nested or highly generic templates hurt a codebase's readability and compile times?advancedTemplates & STL

    Heavy template metaprogramming can produce genuinely difficult-to-read compiler error messages and significantly slower compilation (since each instantiation generates new code) -- templates are a powerful tool, but excessive or unnecessarily generic use trades real readability/build-speed costs for flexibility that may not actually be needed.

  40. Why is reaching for the STL's existing containers/algorithms usually preferred over hand-rolling your own data structures in application-level C++ code?intermediateTemplates & STL

    STL implementations are extensively tested, optimized, and well-understood by other C++ developers reading the code -- hand-rolled equivalents duplicate this effort, are more likely to contain subtle bugs, and are less immediately recognizable to someone else reading the codebase, unless there's a genuinely specific reason the STL's options don't fit.

  41. What is inheritance in C++, and what does `class Dog : public Animal` establish?intermediateInheritance & Polymorphism

    It establishes that `Dog` derives from `Animal`, inheriting its public/protected members -- `Dog` is considered a specialization ('is-a') of `Animal`, gaining its base class's interface/implementation while being able to add its own additional members or override behavior.

  42. What is a virtual function, and what does it enable that a plain (non-virtual) member function does not?advancedInheritance & Polymorphism

    A `virtual` function enables runtime polymorphism -- calling it through a BASE class pointer/reference actually invokes the DERIVED class's overridden version (if one exists), determined at runtime based on the object's real type, rather than the compile-time static type of the pointer/reference.

    class Animal {
    public:
      virtual std::string sound() { return "..."; }
    };
    class Dog : public Animal {
    public:
      std::string sound() override { return "Woof"; }
    };
  43. Why must a base class's destructor be declared `virtual` if the class is meant to be used polymorphically (deleted through a base class pointer)?advancedInheritance & Polymorphism

    Without a virtual destructor, deleting a derived object through a BASE class pointer only calls the base class's destructor, not the derived class's -- this can leave derived-class-specific resources leaked/improperly cleaned up, a genuinely common and serious C++ bug.

    Common mistake: Omitting virtual on a base class destructor when the class is used polymorphically, causing derived-class cleanup to be silently skipped.

  44. What is a pure virtual function (`virtual void draw() = 0;`), and what does it make the containing class?advancedInheritance & Polymorphism

    A virtual function with no implementation in the base class, declared with `= 0` -- a class containing at least one pure virtual function becomes an ABSTRACT class, which cannot be instantiated directly; derived classes must provide an implementation to become instantiable.

  45. What does the `override` keyword do when placed after an overriding method's declaration?advancedInheritance & Polymorphism

    It's a compile-time check confirming the method actually overrides a virtual function from a base class -- if you mistype the signature (wrong parameters, missing `const`), `override` causes a compile error instead of silently defining a new, unrelated method that never actually overrides anything.

    Common mistake: Slightly mistyping an overriding method's signature without the override keyword, silently creating an unrelated new method instead of a real override.

  46. What is the difference between public, protected, and private inheritance in C++?advancedInheritance & Polymorphism

    Public inheritance (by far the most common) preserves the base class's access levels as-is in the derived class ('is-a' relationship); protected and private inheritance downgrade the base class's public/protected members to protected or private respectively in the derived class, generally used for more specialized implementation-inheritance scenarios rather than a genuine is-a relationship.

  47. What is 'slicing' in C++ inheritance, and how does it happen?advancedInheritance & Polymorphism

    Assigning a derived-class object to a BASE-class object BY VALUE (not by pointer/reference) copies only the base-class portion, discarding the derived-class-specific data -- a subtle bug where polymorphic behavior is unintentionally lost because the object was passed/stored by value instead of by pointer or reference.

  48. What is multiple inheritance, and what classic problem (the 'diamond problem') can it introduce?advancedInheritance & Polymorphism

    A class inheriting from more than one base class -- the diamond problem occurs when two base classes both inherit from a common ancestor, and a further-derived class inheriting from both ends up with two separate copies of that ancestor's data unless `virtual` inheritance is explicitly used to share a single instance.

  49. Why might composition ('has-a,' holding another object as a member) be preferred over inheritance ('is-a') in many real designs?advancedInheritance & Polymorphism

    Composition creates a looser coupling than inheritance -- a composed object's implementation details don't leak into or constrain the containing class the way a base class's implementation can constrain its subclasses -- inheritance should generally be reserved for genuine is-a relationships, not just reused for convenient code sharing.

  50. How does runtime polymorphism (via virtual functions) differ from compile-time polymorphism (via templates/function overloading)?advancedInheritance & Polymorphism

    Runtime polymorphism resolves WHICH function implementation actually runs at runtime, based on the object's real type (via a virtual function table lookup); compile-time polymorphism (templates, overloading) resolves everything at COMPILE time, with no runtime dispatch cost -- both achieve a form of 'same interface, different behavior,' via genuinely different mechanisms with different performance tradeoffs.