Virtual destructor in polymorphic classes

I understand that whenever you have a polymorphic base class, the base class must define a virtual destructor. Thus, when the pointer of the base class to the object of the derived class is deleted, it will first call the destructor of the derived class. Correct me if I am wrong here.

also, if the base class destructor should not be virtual, there would be undefined behavior to remove the pointer to the base class for the derived object. Correct me if I am wrong.

, so my question is: why, exactly, when the base class destructor is not virtual, the object will not be destroyed correctly?

I assume that this is due to the fact that virtual functions have some kind of table that is remembered and processed whenever a virtual function is called. And the compiler knows that when an object needs to be deleted, it must first call a derived destructor.

Is my assumption correct?

+4
source share
2 answers

If at the point where you delete the object, the static type of the variable is the base type, then the destructor of the base type will be called, but the destructor of the subclass will not be called (since it is not virtual).

As a result, resources allocated by the base class will be freed, but resources allocated by the subclass will not.

Thus, the object will not be destroyed correctly.

: "vtable". , , (es) !

+7

struct Base {
    void f() { printf("Base::f"); }
};
struct Derived : Base {
    void f() { printf("Derived::f"); }
};
Base* p = new Derived;
p->f();

Base::f, Base::f . :

struct Base {
    ~Base() { printf("Base::~Base"); }
};
struct Derived : Base {
    ~Derived() { printf("Derived::~Derived"); }
};
Base* p = new Derived;
p->~Base();

Base::~Base. , , , , . ( "" ):

struct Base {
    virtual ~Base() { printf("Base::~Base"); }
};
struct Derived : Base {
    ~Derived() override { printf("Derived::~Derived"); }
};
Base* p = new Derived;
p->~Base();

p->~Base() Derived::~Derived(). , , , . ,

Derived::~Derived
Base::~Base

- , .

delete p;

p->~Base();
::operator delete(p);

, , : Derived::~Derived, Base::~Base, . , , Base::~Base.

+2

All Articles