ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base {
Base() { cout << "CtorBase "; }
virtual ~Base() { cout << "DtorBase "; }
};
struct Derived : Base {
Derived() { cout << "CtorDerived "; }
~Derived() { cout << "DtorDerived "; }
};
int main() {
Base *p = new Derived();
delete p;
}- A. CtorBase CtorDerived DtorDerived DtorBase
- B. CtorDerived CtorBase DtorBase DtorDerived
- C. CtorBase CtorDerived DtorBase DtorDerived
- D. CtorDerived CtorBase DtorDerived DtorBase
Correct answer: A. CtorBase CtorDerived DtorDerived DtorBase
Construction always runs base-first then derived (CtorBase, CtorDerived). Because ~Base is virtual, delete p correctly destroys the full Derived object, and destructors always run in the reverse order of construction: derived first, then base (DtorDerived, DtorBase).
More OOP with C++ and Java questions
- What is printed? cpp struct Shape { virtual double area() const { return 0; } virtual void print() const { cout << "Area: " << area(); }…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { } class C extends B { public String…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; A::f(); } }; int…
- What is printed? java class Vehicle { int wheels() { return 4; } } class Motorcycle extends Vehicle { @Override int wheels() { return 2; }…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…
- What is printed? java interface Greeter { default String hello() { return "Hi"; } } class Formal implements Greeter { @Override public…