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;
}- A. ~Derived ~Base, same as if it were virtual
- B. Compilation error: cannot delete a Base* pointing to Derived
- C. ~Base ~Derived
- 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
- What is printed? cpp struct A { virtual void f(int x) { std::cout << "A::f(int) " << x; } }; struct B : A { virtual void f(double x) {…
- What is printed? cpp struct Base { virtual void f() const { std::cout << "Base::f const"; } }; struct Derived : Base { void f() {…
- What is printed? cpp struct IWalk { virtual void move() = 0; }; struct ISwim { virtual void move() = 0; }; struct Duck : IWalk, ISwim {…
- What is printed? cpp struct Base { static void hello() { std::cout << "Base::hello"; } }; struct Derived : Base { static void hello() {…
- What is printed? cpp struct Base { virtual Base clone() { std::cout << "Base::clone "; return new Base(this); } }; struct Derived : Base {…
- What is printed? cpp class Base { public: Base() { std::cout << "Base() "; } virtual void show() { std::cout << "Base::show"; } }; class…