Why should the destructor of base classes be virtual?

前端 未结 5 1278
长情又很酷
长情又很酷 2021-02-05 19:14

in C++: Why should the destructor of base classes be virtual?

5条回答
  •  情话喂你
    2021-02-05 19:50

    The better question is when and why. Your question indicates that you think all base classes should have virtual destructors, which is not quite true.

    It would make it impossible to apply the empty base class optimization, and could multiply the size of classes up to 16 times than what it would be without virtual on common platforms.

    A virtual destructor is needed when you delete an object whose dynamic type is DerivedClass by a pointer that has type BaseClass*. The virtual makes the compiler associate information in the object making it able to execute the derived class destructor. Missing the virtual in such case causes undefined behavior.

    If you don't need this, and your class is only used as a base class, it's best to make the destructor protected, thus preventing that users accidentally delete in the described way.

提交回复
热议问题