Virtual Destructors in Polymorphic Base Classes

Problem Statement: Non-Virtual Destructors in Polymorphic Inheritance

  • Object Setup and Class Hierarchy:

    • A base class dog defines a destructor that prints dog destroyed.
    • A derived class yellow dog inherits from dog and defines its own destructor printing yellow dog destroyed.
    • The Factory design pattern is implemented via a dog Factory class, serving as a centralized interface for instantiating various types of dog objects.
    • The dog Factory class includes a static method named create yellow dog, which instantiates a yellow dog on the heap and returns it upcasted as a base dog raw pointer (dog*).
  • Execution Failure with Non-Virtual Destructors:

    • In the main function, a pointer PD of type dog* is assigned the return value of dog Factory::create yellow dog().
    • When explicit memory deallocation is performed via delete PD, only the base class destructor (dog destructor) is invoked, outputting solely dog destroyed.
    • Because the yellow dog destructor is never executed, the object is only partially destroyed. This leads to incomplete resource cleanup, memory leaks, and undefined behavior.