I have a solid understanding of most OO theory but the one thing that confuses me a lot is virtual destructors.
I thought that the destructor always gets called no matter what and for every object in the chain.
When are you meant to make them virtual and why?
A virtual constructor is not possible but virtual destructor is possible. Let us experiment....
The above code output the following:
The construction of derived object follow the construction rule but when we delete the "b" pointer(base pointer) we have found that only the base destructor is call.But this must not be happened. To do the appropriate thing we have to make the base destructor virtual. Now let see what happen in the following:
The output changed as following:
So the destruction of base pointer(which take an allocation on derived object!) follow the destruction rule i.e first the derived then the base. On the other hand for constructor there are nothing like virtual constructor.
Calling destructor via a pointer to a base class
Virtual destructor call is no different from any other virtual function call.
For
base->f()
, the call will be dispatched toDerived::f()
, and it's the same forbase->~Base()
- its overriding function - theDerived::~Derived()
will be called.Same happens when destructor is being called indirectly, e.g.
delete base;
. Thedelete
statement will callbase->~Base()
which will be dispatched toDerived::~Derived()
.Abstract class with non-virtual destructor
If you are not going to delete object through a pointer to its base class - then there is no need to have a virtual destructor. Just make it
protected
so that it won't be called accidentally:I think the core of this question is about virtual methods and polymorphism, not the destructor specifically. Here is a clearer example:
Will print out:
Without
virtual
it will print out:And now you should understand when to use virtual destructors.
Make the destructor virtual whenever your class is polymorphic.
What is a virtual destructor or how to use virtual destructor
A class destructor is a function with same name of the class preceding with ~ that will reallocate the memory that is allocated by the class. Why we need a virtual destructor
See the following sample with some virtual functions
The sample also tell how you can convert a letter to upper or lower
From the above sample you can see that the destructor for both MakeUpper and MakeLower class is not called.
See the next sample with the virtual destructor
The virtual destructor will call explicitly the most derived run time destructor of class so that it will be able to clear the object in a proper way.
Or visit the link
https://web.archive.org/web/20130822173509/http://www.programminggallery.com/article_details.php?article_id=138
To be simple, Virtual destructor is to destruct the resources in a proper order, when you delete a base class pointer pointing to derived class object.