Why base class destructor (virtual) is called when a derived class object is deleted?

后端 未结 7 792
再見小時候
再見小時候 2020-12-13 13:45

A difference between a destructor (of course also the constructor) and other member functions is that, if a regular member function has a body at the derived class, only the

相关标签:
7条回答
  • 2020-12-13 14:40

    Constructor and destructor are different from the rest of regular methods.

    Constructor

    • can't be virtual
    • in derived class you either call explicitly constructor of base class
    • or, in case where you don't call base class constructor compiler will insert the call. It will call the base constructor without parameters. If no such constructor exists then you get compiler error.

    struct A {};
    struct B : A { B() : A() {} };
    
    // but this works as well because compiler inserts call to A():
    struct B : A { B() {} };
    
    // however this does not compile:
    struct A { A(int x) {} };
    struct B : A { B() {} };
    
    // you need:
    struct B : A { B() : A(4) {} };
    

    Destructor:

    • when you call destructor on derived class over a pointer or a reference, where the base class has virtual destructor, the most derived destructor will be called first and then the rest of derived classes in reversed order of construction. This is to make sure that all memory has been properly cleaned. It would not work if the most derived class was called last because by that time the base class would not exists in memory and you would get segfault.

    struct C
    {
        virtual ~C() { cout << __FUNCTION__ << endl; }
    };
    
    struct D : C
    {
        virtual ~D() { cout << __FUNCTION__ << endl; }
    };
    
    struct E : D
    {
        virtual ~E() { cout << __FUNCTION__ << endl; }
    };
    
    int main()
    {
        C * o = new E();
        delete o;
    }
    

    output:

    ~E
    ~D
    ~C
    

    If the method in base class is marked as virtual all the inherited methods are virtual as well so even if you don't mark the destructors in D and E as virtual they will still be virtual and they still get called in the same order.

    0 讨论(0)
提交回复
热议问题