Question Banks

C++ Coding & Output Questions

30 tricky C++ questions covering virtual dispatch, object slicing, move semantics, and undefined behavior

Q1: What does this print?

#include <iostream>
struct Base {
    virtual void foo() { std::cout << "Base\\n"; }
    ~Base() { foo(); } // Non-virtual destructor calling virtual
};
struct Derived : Base {
    void foo() override { std::cout << "Derived\\n"; }
};
int main() { Derived d; }

Answer: Prints "Base" during destruction, the dynamic type reverts to the current class being destroyed. Virtual dispatch in destructors calls the base version.

Q2: Move Semantics Trap

std::string a = "hello";
std::string b = std::move(a);
std::cout << a.size();  // What value?

Answer: Implementation-defined but valid. After move, a is in a valid-but-unspecified state. Most implementations: 0.

Q3: RAII and Exception Safety

Question: Design a thread-safe singleton using RAII that is exception-safe during construction.

Expected: Meyer's Singleton with static local (C++11 guarantees thread-safe initialization). Discuss double-checked locking anti-pattern.

Topics Covered

  • Virtual dispatch and vtable mechanics
  • Object slicing and polymorphic containers
  • Smart pointer ownership semantics
  • Template metaprogramming (SFINAE, concepts)
  • Memory ordering and atomics
  • Constexpr evaluation
  • Lambda capture pitfalls