tags:

views:

69

answers:

3

Can anybody explain me the concept of virtual destructor ? and also how it is taken care in dotnet ?

+1  A: 

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.

Ben
ok.still need more clarity.
muthukumarm
sure, do you know how virtual methods work?If not, do some reading. Read this:http://en.wikipedia.org/wiki/Virtual_function#Virtual_destructorsto learn about how virtual methods work. This is crucial if you want to understand why destructors need to be virtual.In the latter part of this article is the explanation about virtual destructor specifically.
Ben
If a destructor must always be declared as virtual then why is it legal to declare one as non-virtual?
Eric Lippert
One reason I could think of - If you are not using polymorphism than the definition the destructor as virtual would force the creation of a vtable (In c++, vtable is only created if there is one or more virtual methods in a class).C++ allows the programmer to activate the polymorphism mechanism only on demand and so if there is no need for it, no reason to declare the d'tor virtual.
Ben
A: 

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.

Lucero
A: 

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

Sergey Teplyakov