ProgrammingVery hardProduct company OA

What is the behavior?

What is the behavior?
struct Base {
    ~Base() { std::cout << "~Base "; } // NOT virtual
};
struct Derived : Base {
    int *data = new int[10];
    ~Derived() { delete[] data; std::cout << "~Derived "; }
};
int main() {
    Base *p = new Derived();
    delete p;
}
  1. A. ~Derived ~Base, same as if it were virtual
  2. B. Compilation error: cannot delete a Base* pointing to Derived
  3. C. ~Base ~Derived
  4. D. Undefined behavior: deleting a Derived object through a non-virtual Base* destructor only runs ~Base, leaking Derived's resources

Correct answer: D. Undefined behavior: deleting a Derived object through a non-virtual Base* destructor only runs ~Base, leaking Derived's resources

Without a virtual destructor, `delete p` only calls Base's destructor (based on the static type Base*), never reaching ~Derived() — this leaks the dynamically allocated data array and is technically undefined behavior per the standard for deleting through a pointer to a non-virtual base of a different dynamic type.

More OOP with C++ and Java questions

Exams that ask this topic