ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base {
public:
    virtual ~Base() { cout << "~Base "; }
};
struct Derived : Base {
    int *data = new int[10];
    ~Derived() { delete[] data; cout << "~Derived "; }
};
int main() {
    Base *p = new Derived();
    delete p;
}
  1. A. ~Base
  2. B. ~Derived ~Base
  3. C. ~Base ~Derived
  4. D. Nothing is printed: deleting through a Base* is undefined behaviour here

Correct answer: B. ~Derived ~Base

Because ~Base() is virtual, delete p correctly dispatches to ~Derived() first (running its cleanup and printing ~Derived), and destructors then run base-to-derived in reverse construction order, so ~Base runs afterward, printing ~Derived ~Base.

More OOP with C++ and Java questions

Exams that ask this topic