Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

C++

Interview questions & answers

OOP, RAII, STL, move semantics, modern C++.

102 questions

  1. Question 1

    What is C++?

    Multi-paradigm extension of C with classes, templates, RAII, exceptions, and a large standard library—backward compatible-ish with C.

    Example code

    #include <iostream>
    int main() { std::cout << "C++\n"; }
  2. Question 2

    RAII?

    Resource Acquisition Is Initialization: constructors acquire, destructors release—ties lifetimes to scopes for leaks safety.

    Example code

    class File { int fd; public: File(int f):fd(f){} ~File(){ /* close */ } };
  3. Question 3

    Rule of Three/Five/Zero?

    If you manage raw resources, define copy/move/dtor appropriately—or prefer smart pointers/containers for rule of zero.

    Example code

    class R { int* p; public: R(int x):p(new int(x)){} ~R(){delete p;} R(const R&)=delete; R& operator=(const R&)=delete; };
  4. Question 4

    smart pointers?

    unique_ptr exclusive ownership; shared_ptr refcounted; weak_ptr breaks cycles—prefer unique_ptr by default.

    Example code

    #include <memory>
    auto u = std::make_unique<int>(3);
  5. Question 5

    What is a destructor?

    ~T() runs on scope exit, delete, or exception unwind—must not throw; virtual dtor if polymorphic delete through base.

    Example code

    struct B { virtual ~B()=default; };
  6. Question 6

    Virtual functions?

    Dynamic dispatch via vtable; override in derived; pure virtual = 0 makes class abstract.

    Example code

    struct D : B { void f() override {} };
  7. Question 7

    vtable cost?

    Indirection and inhibited devirtualization vs CRTP/static polymorphism—trade clarity vs performance.

    Example code

    // virtual calls: *(void***)obj is vptr; indirect jump through vtable
  8. Question 8

    Constructor initialization list?

    Initialize bases and members before body runs—required for const, references, base classes without default ctor.

    Example code

    struct Q { int a, b; Q(): a(1), b(2) {} }; // ctor initializer list
  9. Question 9

    explicit constructors?

    Prevent implicit conversions from single-argument constructors—reduce surprise overload resolutions.

    Example code

    struct E { explicit E(int) {} }; // E x = 1; would not compile
  10. Question 10

    Copy vs move?

    Copy duplicates resources; move transfers ownership leaving source in valid unspecified state—move enables cheap returns.

    Example code

    std::vector<int> v{1,2,3};
  11. Question 11

    std::move?

    Casts to rvalue reference to enable move overloads—doesn't move by itself; name is misleading for beginners.

    Example code

    explicit S(int){}
  12. Question 12

    lvalue vs rvalue?

    lvalue has identity; rvalue often temporary; xvalues from std::move; drives overload resolution and move semantics.

    Example code

    std::string a = "hi";
    std::string b = std::move(a);
  13. Question 13

    Perfect forwarding?

    std::forward with universal references preserves value category in templates—used in wrappers like make_unique.

    Example code

    int x = 0;
    int&& r = std::move(x);
  14. Question 14

    Templates?

    Compile-time polymorphism; code bloat risk; SFINAE, concepts (C++20) constrain overload sets.

    Example code

    auto id = [](auto x) { return x; };
  15. Question 15

    Concepts C++20?

    Named requirements on template parameters—clearer errors than SFINAE tricks.

    Example code

    template<typename T> T twice(T x){ return x+x; }
  16. Question 16

    auto and decltype?

    Type deduction reduces verbosity; decltype(auto) preserves references—watch dangling with auto&& to temporaries.

    Example code

    template<std::integral T> T abs(T x){ return x<0?-x:x; }
  17. Question 17

    Range-for?

    Uses begin/end; beware invalidation while mutating containers being iterated.

    Example code

    auto x = 1; decltype(x) y = 2;
  18. Question 18

    std::vector growth?

    Amortized constant push_back; reserve when size known; iterator invalidation rules on reallocation.

    Example code

    for (int n : v) std::cout << n;
  19. Question 19

    std::string?

    SSO on many libs; contiguous data since C++11; pass string_view (C++17) to avoid copies in read-only APIs.

    Example code

    std::vector<int> v; v.reserve(100); v.push_back(1);
  20. Question 20

    string_view lifetime?

    Non-owning reference—must not point to freed temporaries; classic footgun crossing async boundaries.

    Example code

    std::string_view sv = "abc";
  21. Question 21

    std::array vs vector?

    Fixed stack size vs dynamic heap; array keeps size in type for cheap stack buffers.

    Example code

    std::array<int,3> a{1,2,3};
  22. Question 22

    std::map vs unordered_map?

    Balanced tree vs hash table—ordering vs average O(1); define hash for custom keys in unordered.

    Example code

    std::map<std::string,int> m{{"a",1}};
  23. Question 23

    Iterators categories?

    input/output/forward/bidirectional/random access—algorithms require minimum category.

    Example code

    std::unordered_map<std::string,int> h;
  24. Question 24

    STL algorithms?

    Prefer standard algorithms over raw loops for clarity—know complexity and iterator requirements.

    Example code

    std::sort(v.begin(), v.end());
  25. Question 25

    Lambdas?

    Closure objects; capture by value/reference; mutable lambdas; generic lambdas auto params (C++14).

    Example code

    auto lam = [x=1](int y){ return x+y; };
  26. Question 26

    Exceptions?

    stack unwinding calls destructors; noexcept affects move in vectors; don't throw from dtor.

    Example code

    try { throw 1; } catch(int e) { }
  27. Question 27

    Exception safety guarantees?

    Basic, strong, noexcept—document for containers and transactional operations.

    Example code

    S operator+(S a, S b){ return {}; }
  28. Question 28

    Operator overloading?

    Make meaning obvious; preserve expectations; free functions for symmetry (e.g. operator<<).

    Example code

    class F { friend std::ostream& operator<<(std::ostream&, const F&); };
  29. Question 29

    friend keyword?

    Grants access to private members—breaks encapsulation minimally; sometimes needed for operators.

    Example code

    struct D : B1, B2 {};
  30. Question 30

    Multiple inheritance?

    Diamond problem—virtual inheritance mitigates; prefer composition or interfaces.

    Example code

    template<class D> struct B { void f(){ static_cast<D*>(this)->impl(); } };
  31. Question 31

    CRTP?

    Curiously Recurring Template Pattern for static polymorphism—no virtual cost; harder to read.

    Example code

    std::jthread t([]{ std::cout<<"run\n"; });
  32. Question 32

    std::thread?

    Join or detach—destructor std::terminate if still joinable; prefer RAII wrapper or jthread (C++20).

    Example code

    std::mutex m; { std::lock_guard g(m); /* ... */ }
  33. Question 33

    mutex and lock_guard?

    RAII lock; use unique_lock when need to unlock mid-scope or with condition_variable.

    Example code

    std::condition_variable cv; std::unique_lock lk(m); cv.wait(lk, pred);
  34. Question 34

    condition_variable?

    Wait with predicate loop to handle spurious wakeups; avoid lost signals.

    Example code

    std::atomic<int> a{0}; a.fetch_add(1, std::memory_order_relaxed);
  35. Question 35

    memory_order atomics?

    Relaxed/acquire/release for lock-free structures—expert territory; data races are UB.

    Example code

    auto fut = std::async(std::launch::async, []{ return 1; });
  36. Question 36

    std::async?

    Launch policy async vs deferred unclear—often prefer packaged_task and explicit threads for control.

    Example code

    constexpr int sq(int x){ return x*x; }
  37. Question 37

    constexpr?

    Compile-time evaluation when possible—C++20 consteval for must-compile-time.

    Example code

    inline namespace v2 { void api(); }
  38. Question 38

    inline namespace?

    ABI versioning and ADL tricks—library evolution pattern.

    Example code

    namespace N { struct X{}; void swap(X&,X&); }
  39. Question 39

    ADL (Koenig lookup)?

    Unqualified calls also search namespaces of argument types—enables swap idioms and operators.

    Example code

    template<class T> std::enable_if_t<std::is_integral_v<T>,T> f(T x){return x;}
  40. Question 40

    SFINAE?

    Substitution Failure Is Not An Error—enables enable_if tricks before concepts.

    Example code

    std::optional<int> o = 3;
    if (o) std::cout << *o;
  41. Question 41

    What is std::optional (C++)?

    Represents absent value without sentinel; no unexpected null like pointers—watch value() vs value_or.

    Example code

    std::variant<int,std::string> v = "hi";
    std::visit([](auto&& x){ std::cout << x; }, v);
  42. Question 42

    What is std::variant (C++)?

    Type-safe union; visit pattern for dispatch—bad_variant_access if wrong state.

    Example code

    std::any a = 1;
    std::cout << std::any_cast<int>(a);
  43. Question 43

    What is std::any (C++)?

    Type-erased single value—runtime type checks; performance cost vs templates.

    Example code

    std::vector<int> v{1,2,3};
    std::span<int> s{v};
  44. Question 44

    What is std::span (C++)?

    Non-owning contiguous view—bounds-safe-ish API for arrays/vectors in C++20.

    Example code

    std::cout << std::format("x={}", 1);
  45. Question 45

    What is std::format (C++)?

    Type-safe formatting replacing printf/iostreams ergonomics—C++20 feature adoption growing.

    Example code

    std::jthread t([]{ });
  46. Question 46

    What is std::jthread (C++)?

    Joining thread with stop_token cooperative cancellation—C++20 improves thread RAII.

    Example code

    std::latch l(1); l.count_down(); l.wait();
  47. Question 47

    What is std::latch and barrier (C++)?

    Coordination primitives for parallel algorithms—know differences vs counting semaphores.

    Example code

    auto p = std::filesystem::path("a/b");
  48. Question 48

    What is std::filesystem (C++)?

    Portable path operations—exceptions vs error_code overloads for robust tools.

    Example code

    auto t0 = std::chrono::steady_clock::now();
  49. Question 49

    What is std::chrono (C++)?

    Durations and clocks—avoid mixing clock types; use steady_clock for intervals.

    Example code

    std::mt19937 g(std::random_device{}());
    std::uniform_int_distribution<int> d(1,6);
  50. Question 50

    What is std::random (C++)?

    Proper RNG engines and distributions—rand() discouraged for quality randomness.

    Example code

    std::regex r("\\d+");
    std::smatch m; std::regex_search("a1", m, r);
  51. Question 51

    What is std::regex (C++)?

    Convenient but can be slow—consider RE2 for untrusted patterns to avoid catastrophic backtracking.

    Example code

    // prefer {fmt} or std::format
  52. Question 52

    What is iostreams vs fmt (C++)?

    iostreams type-safe but heavy compile; fmt/format faster compile and clearer errors.

    Example code

    static_assert(std::is_trivially_copyable_v<int>);
  53. Question 53

    What is POD trivial types (C++)?

    Legacy terminology evolved—trivially copyable matters for memcpy/memset legality.

    Example code

    auto p = new(std::align_val_t{64}) T();
  54. Question 54

    What is aligned new (C++)?

    Over-aligned types may need aligned new/delete—placement new alignment rules.

    Example code

    int* p = new int(1); delete p;
  55. Question 55

    What is new/delete vs malloc (C++)?

    new calls constructors; malloc raw bytes—mixing delete on malloc is UB.

    Example code

    alignas(T) unsigned char buf[sizeof(T)];
    T* t = new (buf) T(); t->~T();
  56. Question 56

    What is placement new (C++)?

    Construct object in preallocated storage—must manually call destructor.

    Example code

    std::vector<std::unique_ptr<B>> items;
  57. Question 57

    What is Rule of zero with containers (C++)?

    vector<unique_ptr<T>> manages polymorphic objects—clone patterns if copying needed.

    Example code

    struct B { virtual ~B()=default; };
  58. Question 58

    What is Virtual destructor (C++)?

    Base class polymorphic use requires virtual ~Base to delete derived via base pointer.

    Example code

    D d; B b = d; // slices
  59. Question 59

    What is slicing problem (C++)?

    Assigning derived to base by value truncates—use pointers or references for polymorphism.

    Example code

    std::vector<std::unique_ptr<B>> v;
  60. Question 60

    What is Object slicing in vectors (C++)?

    vector<Base> stores bases only—use vector<unique_ptr<Base>> for polymorphic collections.

    Example code

    std::function<int(int)> f = [](int x){ return x; };
  61. Question 61

    What is std::function overhead (C++)?

    Type erasure and possible heap allocation—hot paths may prefer templates.

    Example code

    auto g = [](int a,int b){ return a+b; };
  62. Question 62

    What is std::bind vs lambdas (C++)?

    Lambdas clearer and often faster—bind mostly legacy style.

    Example code

    template<class...A> Wrapper(A&&...a):t(std::forward<A>(a)...){}
  63. Question 63

    What is Perfect ctor forwarding (C++)?

    Forwarding references compete with copy ctor—enable_if/disable_if patterns historically.

    Example code

    struct B { explicit operator bool() const { return true; } };
  64. Question 64

    What is Explicit conversion operators (C++)?

    operator bool explicit avoids implicit conversion surprises.

    Example code

    enum class E { A, B };
  65. Question 65

    What is enum class (C++)?

    Scoped strongly typed enums—prefer over plain enum for new code.

    Example code

    using enum E;
  66. Question 66

    What is using enum (C++)?

    C++20 brings enum members into scope locally—reduces verbosity carefully.

    Example code

    auto [x,y] = std::pair{1,2};
  67. Question 67

    What is Structured bindings (C++)?

    Decompose tuple/pair/struct members—clean iteration over map entries.

    Example code

    if (auto it = m.find(k); it != m.end()) {}
  68. Question 68

    What is if/switch initializers (C++)?

    C++17 limit scope of init variables in condition—safer than outer declarations.

    Example code

    std::byte b{0x01};
  69. Question 69

    What is std::byte (C++)?

    Distinct byte type for memory buffers—avoid char/unsigned char ambiguity for bits.

    Example code

    char buf[32]; auto r = std::to_chars(buf, buf+32, 12345);
  70. Question 70

    What is std::to_chars/from_chars (C++)?

    Fast locale-independent number parsing/formatting—preferred in hot paths.

    Example code

    std::vector<bool> vb{true,false};
  71. Question 71

    What is std::vector<bool> specialization (C++)?

    Packed bits—not a true container of bool references—gotcha for templates expecting T&.

    Example code

    std::string s = "hi";
  72. Question 72

    What is Small string optimization (C++)?

    std::string keeps short strings internal—iterators may invalidate less obviously.

    Example code

    v.push_back(maybe_realloc);
  73. Question 73

    What is Iterator invalidation vector (C++)?

    Insert/erase may invalidate all iterators—use indexes or careful algorithms.

    Example code

    // iterators may invalidate on insert middle
  74. Question 74

    What is deque iterator invalidity (C++)?

    More complex than vector—middle insert invalidates more than ends in implementations.

    Example code

    std::list<int> a{1}, b{2}; a.splice(a.end(), b);
  75. Question 75

    What is list splice (C++)?

    O(1) move nodes between lists—no element copy if node-based ownership moved.

    Example code

    std::priority_queue<int> pq; pq.push(3); pq.push(1);
  76. Question 76

    What is priority_queue (C++)?

    Heap via underlying container—know no efficient update; often use custom heaps for Dijkstra.

    Example code

    struct H { size_t operator()(const std::string& s) const noexcept { return std::hash<std::string>{}(s); } };
  77. Question 77

    What is unordered_map hash quality (C++)?

    Poor hash enables attacker collisions—secure_hash or randomized seed for untrusted keys.

    Example code

    std::vector<int, MyAlloc<int>> v;
  78. Question 78

    What is Custom allocator (C++)?

    STL containers accept allocators—game engines use pool allocators for fragmentation control.

    Example code

    std::pmr::monotonic_buffer_resource pool;
  79. Question 79

    What is pmr (C++17) (C++)?

    Polymorphic memory resources—arena allocators for parse trees and compilers.

    Example code

    auto p = std::make_shared<int>(1);
  80. Question 80

    What is std::shared_ptr control block (C++)?

    Separate allocation with make_shared merges object+control block—performance and exception safety win.

    Example code

    std::weak_ptr<int> w = p; if (auto s = w.lock()) {}
  81. Question 81

    What is weak_ptr use (C++)?

    Break cycles in graphs; lock() to temporarily promote to shared_ptr safely.

    Example code

    struct S : std::enable_shared_from_this<S> { std::shared_ptr<S> me() { return shared_from_this(); } };
  82. Question 82

    What is enable_shared_from_this (C++)?

    Get shared_ptr from this inside object—prevents double control blocks.

    Example code

    std::atomic<std::shared_ptr<int>> ap;
  83. Question 83

    What is std::atomic shared_ptr (C++)?

    C++20 atomic<shared_ptr>—lock-free is complicated; often mutex simpler.

    Example code

    volatile int* reg = (int*)0x4000;
  84. Question 84

    What is volatile in C++ (C++)?

    Not for thread synchronization—use atomics; volatile for hardware registers only.

    Example code

    std::atomic_thread_fence(std::memory_order_seq_cst);
  85. Question 85

    What is memory barriers (C++)?

    std::atomic_thread_fence rare—prefer atomic operations with correct orders.

    Example code

    std::scoped_lock lk(m1, m2);
  86. Question 86

    What is Lock ordering (C++)?

    Global lock order prevents deadlocks—document and enforce across modules.

    Example code

    std::try_lock(m1, m2);
  87. Question 87

    What is try_lock strategies (C++)?

    std::try_lock on multiple mutexes—backoff pattern to avoid deadlock.

    Example code

    thread_local int x;
  88. Question 88

    What is Thread-local storage (C++)?

    thread_local keyword—per-thread globals; initialization rules per implementation.

    Example code

    std::once_flag f; std::call_once(f, []{});
  89. Question 89

    What is std::call_once (C++)?

    One-time initialization flag—singleton pattern without static initialization order fiasco pitfalls.

    Example code

    // construct on first use
  90. Question 90

    What is Static initialization order fiasco (C++)?

    Cross-TU static ctor order undefined—construct on first use idiom mitigates.

    Example code

    if constexpr (std::is_integral_v<T>) { }
  91. Question 91

    What is constexpr if (C++)?

    Compile-time branch in templates—cleaner than SFINAE for many cases.

    Example code

    template<typename T> void g(){ if constexpr (sizeof(T)==4){} }
  92. Question 92

    What is if constexpr in templates (C++)?

    Discards non-taken branch—ODR and template instantiation rules still apply.

    Example code

    import std;
  93. Question 93

    What is Modules C++20 (C++)?

    import std reduces compile times—tooling adoption still maturing in 2024-2026 era.

    Example code

    // co_await in coroutine body
  94. Question 94

    What is Coroutines C++20 (C++)?

    co_await/co_yield stackless coroutines—compiler transforms; promise types complex.

    Example code

    auto v = std::views::iota(1,4);
  95. Question 95

    What is Ranges C++20 (C++)?

    Composable views; lazy evaluation—watch dangling if referencing temporaries in pipelines.

    Example code

    auto r = v | std::views::take(3);
  96. Question 96

    What is Views and lifetimes (C++)?

    filter/transform may reference expired temporaries—materialize when unsure.

    Example code

    template<std::integral T> void f(T x){}
  97. Question 97

    What is Concepts requires clauses (C++)?

    syntax auto f(T t) requires std::integral<T>—clear constraints.

    Example code

    auto operator<=>(const S&) const = default;
  98. Question 98

    What is Three-way comparison <=> (C++)?

    Spaceship operator generates relational ops—= default for memberwise.

    Example code

    S() = default;
  99. Question 99

    What is Rule of zero with = default (C++)?

    Explicitly default special members when needed for clarity or triviality guarantees.

    Example code

    static_assert(noexcept(S(std::move(s))));
  100. Question 100

    What is noexcept move vectors (C++)?

    Vectors move elements only if move ctor is noexcept—otherwise copies on reallocation in older standards nuances.

    Example code

    extern "C" void api(void);
  101. Question 101

    What is ABI stability (C++)?

    Compiler flags and STL versions must match across DLL boundaries—export only C API or stable ABI types.

    Example code

    extern "C" int add(int a,int b);
  102. Question 102

    What is extern C (C++)?

    Disable C++ name mangling for C linkage—required for cross-language APIs.

    Example code

    // cpp — add snippet 102