Can anybody explain me the concept of virtual destructor ? and also how it is taken care in dotnet ?
if you're referring to C++.
A Destructor must always be declared virtual.
Why? Because when the object is "destructed" it has to clear the resources of the object that we are referring to in the code.
See this example to understand :
Class A;
Class B: Public A { int *pVar };
A* x = new B();
delete x
;
In this case, if the destructor of B is not declared as virtual, the destructor that will be called is that of A and so pVar will not be freed. Hope this is clear.
EDIT: If this answers your question please mark it as the answer or at least upvote.
EDIT2: This wiki link describes it very well.
The concept is that each type in the inheritance line up to the root (Object
) have the opportunity to do cleanup. It's basically the same concept as a normal virtual method.
In .NET, the Finalize()
method is basically that. But note that, since .NET is a managed environment with a garbage collector which is not deterministic, the moment at which the Finalize()
method is called is also not deterministic.
If that answers your question, please accept it as answer.
http://en.wikipedia.org/wiki/Virtual_destructor
About destructor and finalizers see great article What’s the difference between a destructor and a finalizer? by Eric Lippert