Search code examples
c++oopcompiler-constructiondestructortheory

Why aren't (C++) virtual destructors enforced for a base class


Destructors aren't virtual by default to not hurt when its not needed, which is fine.

But in case of a base class derived class scenario, is there any use case for not having a virtual destructor? If not could it be possible (does it make sense) for the compiler to complain if a class derives from a base class which has a public non virtual destructor (or no destructor) defined. And not just warn about it.


Solution

  • The problem with your idea is that it's conceivable that someone is using a non-virtual base class destructor as an optimization (if you're never going to destroy via a base-class pointer, then the missing virtual won't hurt you, and still avoids the vtable entry).

    Since it COULD be used, it's allowed. I'd think an optional compiler warning might be a good idea, but not something in the language spec.