How do virtual destructors work?

后端 未结 2 665
情书的邮戳
情书的邮戳 2020-12-17 02:51

I am using gcc. I am aware how the virtual destructors solve the problem when we destroy a derived class object pointed by a base class pointer. I want to know how do they w

相关标签:
2条回答
  • 2020-12-17 03:48

    Virtual destructor is just a virtual function, so it adheres to the same rules.

    When you call delete a, a destructor is implicitly called. If the destructor is not virtual, you get called a->~A(), because it's called as every other non-virtual function.

    However if the destructor is virtual, you get ~B() called, as expected: the destructor function is virtual, so what gets called is the destructor of derived class, not base class.

    Edit:
    Note that the destructor of the base class will be called implicitly after the destructor of the derived class finishes. This is a difference to the usual virtual functions.

    0 讨论(0)
  • 2020-12-17 03:53

    The key thing you need to know is that not using a virtual destructor in the above code is undefined behavior and that's not what you want. Virtual destructors are like any other virtual functions - when you call delete the program will decide what destructor to call right in runtime and that solves your problem.

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