MiddleDebuggingOccasionalNot answered yet
Why might deleting through this Base* leak?
Derived owns resources, yet running this prints only ~Base.
struct Base { ~Base() { std::cout << "~Base "; } }; // non-virtual
struct Derived : Base { ~Derived() { std::cout << "~Derived "; } };
int main() {
Base* p = new Derived();
delete p;
}
Find and fix the bug.
Deleting a Derived through a Base* whose destructor is not virtual is undefined behavior — in practice ~Derived never runs, leaking the resources it owns. Fix: give a polymorphic base a virtual destructor (or own it via unique_ptr).
- ✗Assuming the destructor dispatches virtually without being declared virtual
- ✗Believing the base destructor is enough because the pointer's static type is Base
- ✗Confusing this with object slicing — here the object is intact, only its cleanup is wrong
- →When does a base class NOT need a virtual destructor?
- →How does owning the object via
std::unique_ptr<Base>avoid this bug?