0

I am struggling a bit with the details of using pointers with parent classes as a type, when I want to actually trigger the destructor of child classes. This is my (very simplified version) inheritance structure:

#include <iostream>

class Parent {
  public:
    ~Parent() { std::cout << "Parent destructor" << std::endl; }
};

class ChildA: public Parent {
  public:
    ~ChildA() { std::cout << "ChildA destructor" << std::endl; }
};

class ChildB: public Parent {
  public:
    ~ChildB() { std::cout << "ChildB destructor" << std::endl; }
};

Now, in my main function, I first create an object of ChildA, then destroy it and create an object of ChildB, while using the same pointer to reference to these objects. To do so, I am using Parent as the type of the pointer (again, very simplified version of a real world scenario).

int main() {
  Parent* myObj;
  myObj = new ChildA();
  delete myObj;
  myObj = new ChildB();
  delete myObj;

  return 0;
}

My issue with this is, that this is calling the destructor of the parent class, which always results in printing "Parent destructor" to standard out, rather than "ChildA destructor" and "ChildB destructor". I assumed that it would implicitly call the destructor of the actual (child) class. So my question is, how can I trigger the destructor of the child class when I want to destroy the object and still refer to them with a pointe that uses their parent class as a type?

Sebastian Dine
  • 815
  • 8
  • 23

0 Answers0