ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct B {
    B()  { cout << "b"; }
    ~B() { cout << "~b"; }
};
struct D : B {
    D()  { cout << "d"; }
    ~D() { cout << "~d"; }
};
int main() {
    B* p = new D[2];
    delete[] static_cast<D*>(p);
}
  1. A. bdbd~d~b~d~b
  2. B. bdbd~b~b
  3. C. bbdd~d~d~b~b
  4. D. bdbd~d~b

Correct answer: A. bdbd~d~b~d~b

Each array element is built base first: b d, b d. Deleting through the correct type D* destroys the elements in reverse order, each running ~D then ~B. Deleting the array through a B* would be undefined.

More OOP with C++ and Java questions

Exams that ask this topic