66 C++ interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
C++ is a compiled, statically typed language that gives direct control over memory and resources, used in systems software, games, and performance-sensitive applications. The questions address how C++ differs from C, object-oriented design, pointers and memory management including dangling pointers, the STL and its components, and modern C++ features such as lambda expressions and capture clauses.
C++ extends C with: - OOP: classes, inheritance, polymorphism, encapsulation. - References (&): safer aliases than raw pointers. - new/delete instead of malloc/free — invoke constructors/destructors. - RAII and smart pointers: objects release resources in their destructor when they leave scope, so std::uniqueptr and std::vector…
A reference is an alias for an existing variable — same address, same value, different name. A reference must be initialized at its declaration (int& r; does not compile) and stays bound to x for life. Given another variable y, ref = y does not…
new malloc --------- Type C++ operator C function Size computed from the type (new int[5]) you compute the bytes (malloc(5 sizeof(int))) Constructor Called automatically Not called Destructor delete calls it before freeing free() does not call it Return type pointer of the right type (T)…
Stack: automatic storage for local variables, allocated when a function is called and freed automatically when it returns. Allocation is very fast because it only moves the stack pointer; size is limited (typically a few MB), and going too deep causes a stack overflow. Heap:…
inline in C++ has two meanings. - Optimization hint: asks the compiler to insert the function body at the call site instead of making a call, saving overhead for small functions. It is only a hint: the compiler decides. - Allows defining a function in…
Function overloading: multiple functions with the same name but different signatures (parameter count/types). The compiler picks the right version at compile-time. Operator overloading: redefine operators (+, <<, ==, ...) for user-defined types. Distinct from overriding: override rewrites a base-class method in a subclass (runtime), overloading…
A dangling pointer points to memory that has already been freed — reading or writing through it is undefined behavior (crash or silent data corruption). Setting nullptr after delete only protects that one variable. Any other pointer that copied the address (like alias) still points…
RAII (Resource Acquisition Is Initialization): tie a resource's lifetime (memory, file, lock...) to the lifetime of an object whose destruction time is well-defined: a local variable, a member of another object, a container element, or an object a uniqueptr holds on the heap. Acquire in…
uniqueptr: exclusive ownership — only one owner, not copyable, only movable. Automatically deletes on scope exit. sharedptr: shared ownership — multiple pointers co-own an object via a reference count. Deletes when count reaches zero. weakptr: observer, does not increase ref count — used to break…
Shallow copy (the compiler-generated copy constructor): copies member by member (memberwise) — for pointer members only the address is copied, so, both objects point to the same memory. Freeing one leaves the other with a dangling pointer. Deep copy: copies the content the pointer points…
Rule: const applies to whatever is on its left; if nothing is on its left (const comes first), it applies to what is on its right. The reading trick is right-to-left: int const p reads "p is a const pointer to int". Practical example: Mental…
1. Encapsulation: bundle data and methods in a class; hide internals via private/protected. 2. Inheritance: a child class inherits properties and methods from a parent class → code reuse and extension. 3. Polymorphism: same interface, multiple behaviors — compile-time (overloading) and runtime (virtual functions). 4.…
Virtual function: has a default implementation in the base class; derived classes may override it. Pure virtual function (= 0): no base-class implementation; derived classes must override it. A class with any pure virtual becomes an abstract class — it cannot be instantiated. The virtual…
When a class has at least one virtual function, the compiler creates a vtable — an array of function pointers for that class. Each object gets a hidden vptr pointing to its actual class's vtable. Calling s-area() (s is Shape pointing to Circle): read vptr…
The diamond problem occurs when class D inherits from both B and C, which both inherit from A. Result: D gets two copies of A, causing ambiguity. Solution: virtual inheritance — A exists only once in D. Virtual inheritance adds overhead (extra vptr); the usual…
The STL (Standard Template Library) is C++'s standard library providing optimized data structures and algorithms via templates. Three main components: 1. Containers: store data. - Sequence: vector, list, deque, array - Associative: set, map, multiset, multimap - Unordered: unorderedmap, unorderedset - Adapters: stack, queue, priorityqueue…
std::vector is a dynamic array that manages a contiguous heap buffer and resizes as needed. - size(): current number of elements. - capacity(): number of elements the buffer can hold before reallocation. When size == capacity and a new element is added, the vector allocates…
std::map std::unorderedmap --------- Internal structure Red-Black Tree Hash Table Key order Sorted Unordered find / insert / erase O(log n) O(1) average, O(n) worst Iterator validity preserved after insert may invalidate after rehash Key requirement operator< std::hash<K + operator== Choose map when: you need sorted…
An iterator is a generalized pointer-like object for traversing containers — decoupling algorithms from container internals. 5 classic categories (least to most capable): Category Read Write ++ -- [] Example --------------------- Input Yes No Yes No No istreamiterator Output No Yes Yes No No ostreamiterator…
A lambda is an anonymous inline function, commonly used with STL algorithms. Capture by value takes the value at the moment the lambda is created: addBase keeps a copy of base = 10, so changing base later does not affect it. Capture by reference makes…
Before C++11, passing large objects (vectors, strings) always copied them — expensive. Move semantics allow transferring resources instead of copying. - lvalue: object with a stable address (addressable with &). - rvalue: temporary value with no persistent address (expression result, literal). - T&& (rvalue reference):…
auto: asks the compiler to deduce the type from the initialization expression. Range-based for (C++11): iterates over each element of a container without an iterator or an index. The type declared at the start of the loop decides whether each element is copied or referenced.…
Before C++11, NULL was typically define NULL 0 — an integer type, causing overload ambiguity. C++11 did not change that: NULL is still the integer constant 0 with no pointer type, so foo(NULL) still does not pick the right overload (it picks int or is…
Undefined behavior is behavior that the C++ standard does not specify an outcome for — the compiler is free to do anything: crash, wrong result, or accidentally "work". Common examples: Situation Why UB ------ int p = nullptr; p = 1; null pointer dereference int…
A memory leak occurs when memory allocated via new/malloc is never freed — the program gradually consumes all available RAM. Common causes: - Forgetting delete (especially with exceptions or early returns) - Losing the pointer before deleting (pointer overwritten) - Circular references between sharedptrs Why…
Cast Timing Use when --------- staticcast compile-time safe conversions: int→double, upcast, void→T dynamiccast runtime (RTTI) downcast through hierarchy — returns nullptr/throws on wrong type reinterpretcast compile-time raw bit reinterpretation — pointer↔integer, completely unsafe constcast compile-time add/remove const/volatile — the cast itself is always valid, but…
explicit prevents the compiler from performing implicit conversions when calling a constructor or conversion operator. With Width, the compiler silently builds a Width from 42, so passing any stray number to process still compiles. explicit forces the caller to write SafeWidth(42). Practical rule: single-argument constructors…
A const member function is declared with const after the parameter list — it commits to not modifying the object's state (cannot modify any non-mutable member). Why it matters (const-correctness): - Allows passing objects by const& and still calling getters. - Compiler catches violations at…
friend lets a function or class directly access the private/protected members of another class — controlled encapsulation breakage. Legitimate uses: - Operator overloading where the left operand is not your class. operator<< for std::ostream is the example: in os << box the os is on…
A static member (variable or function) belongs to the class itself, not to any particular instance — all objects share the same single copy. The three objects a, b, c read and write the same total, so each constructor adds 1 to one shared number…
STL algorithms work on any container through iterators — separating logic from data structure. Note: std::sort on std::list won't compile — list lacks random access iterators; use list.sort() instead.
std::set std::multiset --------- Duplicate keys Not allowed Allowed Structure Red-Black Tree Red-Black Tree insert O(log n) O(log n) Order Sorted (ascending by default) Sorted Use set when: you need a collection of unique elements, O(log n) membership checks. Use multiset when: duplicates must be preserved,…
Mechanism: throw raises an exception, the program leaves the current function and walks back up the callers until it finds a catch with a matching type. The catch blocks are tried from top to bottom and the first matching handler wins. std::invalidargument derives from std::exception,…
std::optional<T represents a value that may or may not be present — a type-safe alternative to nullptr, -1, or a boolean out-parameter. valueor returns exactly T (here User), so the fallback must also be a User, not a string. Use when: a function can legitimately…
std::variant is a type-safe union — holds one value at a time, but always knows which type it is currently holding. On each assignment, the variant destroys the old value and records the new type. After v = "hello" it only holds a std::string, so…
std::stringview is a non-owning view into a character sequence — just a pointer + length, zero copies. vs const std::string&: const std::string& std::stringview --------- const char argument Creates temporary string Does not Taking a substring std::string::substr allocates a new string stringview::substr is zero-copy Non-null-terminated Not…
std::initializerlist<T allows initializing objects with brace syntax {...} using multiple values — especially useful for containers. Priority note: This preferential treatment of initializerlist constructors with {} is a common source of subtle bugs in C++11.
Pass-by-value Pass-by-reference (&) Pass-by-pointer () ------------ Copy Always copies No copy No copy (copies address) Null Cannot be null Cannot be null Can be null Can modify the caller's variable No, the function edits a copy Yes Yes, via p Use case Small types (int,…
A namespace is a named scope for grouping identifiers — preventing name collisions when using multiple libraries. using namespace std; pulls everything from std into the current scope — convenient for small examples but hazardous in real code. Problem in headers: - Headers are included…
Three STL container adapters — built on top of real containers (default deque or vector). Container Order Default base Push Pop Access ------------------ stack LIFO deque O(1) O(1) top() queue FIFO deque O(1) O(1) front() priorityqueue Heap (max at top) vector O(log n) O(log n)…
The only technical difference: the default access level. - struct: members and inheritance are public by default. - class: private by default. Otherwise the two keywords are fully equivalent — a struct can have methods, constructors, inheritance, and templates just like a class. Convention: use…
Prefer const (Effective C++, Item 2: "Prefer consts to defines"). define is just text substitution by the preprocessor: - No type, no scope — it ignores namespaces and classes. - The name is gone before the compiler sees it → the debugger cannot show it,…
Compile-time (static polymorphism): the call is resolved at compile time — via function overloading, templates, or CRTP. No runtime cost and it can inline, but the type must be known at compile time. Runtime (dynamic polymorphism): resolved at run time via virtual functions + a…
When you delete a derived object through a base pointer: If Base destructor is not virtual, only ~Base() runs — the Derived part is never destroyed → resource leak / undefined behavior. Mark virtual ~Base() so delete consults the vtable and calls ~Derived(), destroying the…
volatile tells the compiler that a variable value may change from outside the program flow: hardware registers, interrupts/ISRs, memory-mapped I/O. The compiler then must not optimize by caching the variable in a register or eliminating "redundant" reads — every access must read/write memory directly. Note:…
- delete: destroys a single object (allocated with new). Runs one destructor, then frees the memory. - delete[]: destroys an array (allocated with new[]). Runs the destructor for each element, then frees. They must be paired: new↔delete, new[]↔delete[]. Mixing them (using delete on an array,…
A pointer is a variable that holds the address of another variable in memory. &x takes the address of x, and p (dereference) reads or writes the value at the address stored in p. Pointer arithmetic: p + 1 does not add one byte; it…
A function pointer holds the address of a function instead of the address of data. Calling through it looks like a normal call, but which function runs is decided at run time. It is how C "passes behavior as a parameter" without lambdas. The parentheses…
Every type has an alignment: its address must be a multiple of some number (typically char = 1, int = 4, double and pointers = 8 on x86-64). To put every field at a properly aligned address, the compiler inserts padding — unused bytes —…
extern declares that a variable or function is defined somewhere else (another .c/.cpp file) and is only being used here. It is a declaration, not a definition, so no storage is allocated; the linker connects it to the real definition at link time. The standard…
The two are often confused because both sound "empty", but they describe different things: void is about type, NULL is about value. void is an "untyped" pointer: it can hold the address of any object but does not know what is there. Because the element…
static changes one of two things depending on where it appears: inside a function it changes lifetime, at file scope it changes visibility (linkage). 1. Local static variable — lives for the whole program, is initialized only once, but is still visible only inside the…
The root difference: C++ compiles to machine code and lets you manage memory yourself, while Java runs on the JVM with a garbage collector. Most other differences follow from that. C++ Java --------- Compilation Machine code per OS/CPU Bytecode, interpreted + JIT-compiled by the JVM…
The four usually asked about: default (no parameters), parameterized (with parameters), copy T(const T&) and move T(T&&) (since C++11). There are also delegating constructors (calling another constructor of the same class) and converting constructors (single-argument constructors, which should be marked explicit to prevent implicit conversions).…
All four work with the heap — memory that lives until you release it, unlike local variables on the stack that disappear when the function returns. - malloc(size) — allocates size bytes, uninitialized: the contents are leftover garbage. - calloc(n, size) — allocates n size…