ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Base {
    Base() { cout << "Base-ctor "; }
    ~Base() { cout << "Base-dtor "; }
};
struct Derived : Base {
    Derived() { cout << "Derived-ctor "; }
    ~Derived() { cout << "Derived-dtor "; }
};
int main() {
    Derived d;
}
  1. A. Base-ctor Derived-ctor Derived-dtor Base-dtor
  2. B. Derived-ctor Base-ctor Base-dtor Derived-dtor
  3. C. Base-ctor Derived-ctor Base-dtor Derived-dtor
  4. D. Derived-ctor Base-ctor Derived-dtor Base-dtor

Correct answer: A. Base-ctor Derived-ctor Derived-dtor Base-dtor

Construction always runs base-to-derived (Base-ctor then Derived-ctor), and destruction always runs in exactly the reverse order (Derived-dtor then Base-dtor), regardless of whether the destructor is virtual, since this is non-polymorphic stack destruction of the concrete type.

More OOP with C++ and Java questions

Exams that ask this topic