ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base {
    Base() { cout << "B "; }
    virtual ~Base() { cout << "~B "; }
};
struct Derived : Base {
    int* data;
    Derived() : data(new int[10]) { cout << "D "; }
    ~Derived() override { delete[] data; cout << "~D "; }
};
int main() {
    Base *arr[2];
    arr[0] = new Derived();
    arr[1] = new Derived();
    for (auto p : arr) delete p;
}
  1. A. B D B D ~D ~B ~D ~B
  2. B. B D B D ~B ~D ~B ~D
  3. C. B D D B ~D ~B ~D ~B
  4. D. Memory leak: data is never freed because ~Derived is never called

Correct answer: A. B D B D ~D ~B ~D ~B

Both Derived objects are constructed first (B D, B D). Because Base's destructor is virtual, deleting each Base* correctly invokes the full chain starting at Derived: for each pointer, ~Derived runs first (freeing data, printing ~D) then ~Base (~B), in the order the loop processes arr[0] then arr[1].

More OOP with C++ and Java questions

Exams that ask this topic