ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct M { M() { cout << "m"; } ~M() { cout << "~m"; } };
struct B {
B() { cout << "b"; f(); }
virtual ~B() { cout << "~b"; f(); }
virtual void f() { cout << "B"; }
};
struct D : B {
M m;
D() { cout << "d"; f(); }
~D() { cout << "~d"; f(); }
void f() override { cout << "D"; }
};
int main() { B* p = new D; delete p; }- A. bBmdD~dD~m~bB
- B. bDmdD~dD~m~bD
- C. mbBdD~dD~bB~m
- D. bBmdD~bB
Correct answer: A. bBmdD~dD~m~bB
Construction: base first, then members, then the derived body. While B's constructor runs the object is a B, so f() calls B::f. Then member m is built, then D's body prints d and calls D::f. delete through B* is safe because ~B is virtual: ~D runs (calling D::f), then members are destroyed (~m), then ~B, during which the object is a B again, so f() is B::f. Without the virtual destructor only ~B would run, which is undefined behaviour.
More OOP with C++ and Java questions
- What is printed? cpp struct P { P(const char s) { cout << s; } }; struct B1 { B1() { cout << "1"; } }; struct B2 { B2() { cout << "2"; }…
- What is printed? cpp struct A { A() { } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }; void f(A a) {…
- What is printed? cpp struct B { virtual void f() = 0; }; void B::f() { cout << "B"; } struct D : B { void f() override { cout << "D"…
- What is printed? cpp struct C { static int n; C() { n++; } ~C() { n--; } }; int C::n = 0; void f(C c) { } int main() { C a; f(a); f(a); {…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; void call(const S& s) { s.f(); } int main() {…
- What is printed? cpp struct B { void f(int) { cout << "Bi "; } void f(double) { cout << "Bd "; } }; struct D : B { using B::f; void f(int)…