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.
If your base class destructor is virtual then objects will be destructed in a order(firstly derived object then base ). If your base class destructor is NOT virtual then only base class object will get deleted(because pointer is of base class "Base *myObj"). So there will be memory leak for derived object.
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.
No. You never need to explicitly call a destructor (except with placement new). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.
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.
Because it's perfectly valid to have a non-virtual destructor. If sub classes are only designed to be stack allocated, for example, there's no need for a virtual destructor. Why require clients to have all the vtbl machinery when a class is only supposed to be a decorator?
It also makes little sense to have a virtual destructor when a class is meant to be inherited from privately (implemented-in-terms-of).
This all said, a destructor should usually be public and virtual or protected, unless a class is not meant to be a base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With