Tag Archives: virtual destructor

virtual destructor in C++

In a derived class, if base class has a virtual destructor, then derived class  destructor is automatically virtual. You might need an explicitly defined destructor for other reasons, but there’s no need to redeclare a destructor simply to make sure it is virtual. No matter whether you declare it with the virtual keyword, declare it without the virtual keyword, or don’t declare it for child , it’s still virtual.

When someone says delete using a Base pointer that’s pointing at a Derived object. When you say delete *p, and the class of p has a virtual destructor, the destructor that gets invoked is the one associated with the type of the object *p, not necessarily the one associated with the type of the pointer. So,Virtual Destructor ensures to invoke actual object destructor

If you create an object with default implementations for its virtual methods and want to make it abstract without forcing anyone to override any specific method, you can make the destructor pure virtual.

Pure virtual destructors should have body else if we do not provide the definition for a pure virtual destructor, what function body would be called during destruction? Virtual destructor also causes the class to be abstract.So if no pure virtual fuction in a class , make the destructor as virtual.

If library do not have a virtual destructor, it usually means that the authors of the library do not want you to derive from their class. implementor of the third party do not want their class to be used for polymorphic inheritance.