ProgrammingVery hardTCS NQT Prime · Infosys SP

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct A {
    virtual ~A() { f(); }
    virtual void f() { cout << "A"; }
};
struct B : A {
    ~B() { cout << "b"; }
    void f() override { cout << "B"; }
};
int main() { A* p = new B; delete p; }
  1. A. bA
  2. B. bB
  3. C. B
  4. D. Ab

Correct answer: A. bA

~B runs first and prints b; by the time ~A runs the B part is destroyed, so the virtual call f() resolves to A::f.

More OOP with C++ and Java questions

Exams that ask this topic