ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
struct B {
virtual ~B() { hi(); }
virtual void hi() { cout << "B"; }
};
struct D : B {
~D() { hi(); }
void hi() override { cout << "D"; }
};
int main() { B* p = new D; delete p; }- A. DD
- B. DB
- C. BB
- D. BD
Correct answer: B. DB
The virtual destructor runs ~D first, where hi() dispatches to D. By the time ~B runs the D part is gone and the dynamic type is B, so the virtual call resolves to B::hi.
More OOP with C++ and Java questions
- What is printed? cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }; struct D : B { void f(int x = 2) override { cout << "D"…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { void f(double) { cout <<…
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { using B::f; void…
- What is printed? cpp struct B { virtual char id() const { return 'B'; } }; struct D : B { char id() const override { return 'D'; } }; void…
- What is printed when compiled as C++17? cpp struct T { T() { cout << "c"; } T(const T&) { cout << "k"; } }; T make() { return T(); } int…
- What is printed? cpp struct C { static int n; C() { ++n; } C(const C&) { ++n; } ~C() { --n; } }; int C::n = 0; void f(C c) { cout << C::n…