In C++ Inheritance, Derived class destructor not called when pointer object to base class is pointed to derived class

Your code has undefined behavior. The base class’s destructor must be virtual for the following to have defined behavior.

Base* b = new Derived;    
delete b;

From the C++ standard:

5.3.5 Delete

3 In the first alternative (delete object), if the static type of the
operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

So in your case, the static type is Base, and the dynamic type is Derived. So the Base‘s destructor should be:

virtual ~Base() {cout << "Base Destructor\n"; }

Leave a Comment