A misunderstanding with polymorphism and virtual destructors

215 views Asked by At

Example:

class Base {
  public:
    virtual void f() = 0;
    virtual ~Base() { std::cout << "Base::~Base()\n"; }
};

class Derived : public Base {
  public:
    void f() { }
    ~Derived() { std::cout << "Derived::~Derived()\n"; }
};

int main() {
  Base* p = new Derived();
  delete p;
  return 0;
}

Output:

Derived::~Derived()
Base::~Base()

I thought only the derived class destructor will be called since the pointed object to be freed is an instance of the derived class.

I have two questions:

  1. Why was the virtual base destructor called?
  2. Is it legally possible (or should it even be possible) to prevent the base class destructor from being called?
1

There are 1 answers

0
SergeyA On

Why was the virtual base destructor called?

Because base class should be properly destructed. Derived class can not possibly do this.

Is it legally possible (or should it even be possible) to prevent the base class destructor from being called?

No, because it would prevent properly destructing the base class (i.e. call it's members destructors)