Virtual Destructors in Polymorphic Base Classes
Problem Statement: Non-Virtual Destructors in Polymorphic Inheritance
Object Setup and Class Hierarchy:
- A base class
dogdefines a destructor that printsdog destroyed. - A derived class
yellow doginherits fromdogand defines its own destructor printingyellow dog destroyed. - The Factory design pattern is implemented via a
dog Factoryclass, serving as a centralized interface for instantiating various types of dog objects. - The
dog Factoryclass includes a static method namedcreate yellow dog, which instantiates ayellow dogon the heap and returns it upcasted as a basedograw pointer (dog*).
- A base class
Execution Failure with Non-Virtual Destructors:
- In the
mainfunction, a pointerPDof typedog*is assigned the return value ofdog Factory::create yellow dog(). - When explicit memory deallocation is performed via
delete PD, only the base class destructor (dogdestructor) is invoked, outputting solelydog destroyed. - Because the
yellow dogdestructor is never executed, the object is only partially destroyed. This leads to incomplete resource cleanup, memory leaks, and undefined behavior.
- In the