ProgrammingHardProduct-company placement · C++
What is printed?
What is printed?
struct B {
virtual ~B() { hi(); }
virtual void hi() { cout << "B"; }
};
struct D : B {
~D() { cout << "~D "; }
void hi() override { cout << "D"; }
};
int main() { B* p = new D; delete p; }- A. ~D B
- B. ~D D
- C. B
- D. B ~D
Correct answer: A. ~D B
The virtual destructor runs ~D first, then ~B. By the time ~B runs, the D part is already destroyed and the object's dynamic type is B, so the virtual call hi() inside it resolves to B::hi.
More OOP with C++ and Java questions
- What is printed? cpp struct E { virtual const char what() const { return "E"; } }; struct F : E { const char what() const override {…
- What is printed? cpp struct E { }; struct F : E { }; int main() { try { throw F(); } catch (E&) { cout << "E"; } catch (F&) { cout << "F"…
- What is printed? cpp struct E { virtual void id() const { cout << "E"; } }; struct F : E { void id() const override { cout << "F"; } }…
- What is printed? cpp struct T { char c; T(char x) : c(x) { cout << c; } ~T() { cout << c << c; } }; void f() { T a('a'); T b('b'); throw…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "a"; } }; struct B { B() { cout << "B"; throw 0; } ~B() { cout << "b"…
- What is printed? cpp struct W { W() { cout << "W"; } }; int main() { W w1; W w2(); W w3{}; cout << "!"; }