virtual destructor

2019-06-14 09:11发布

问题:

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

回答1:

Following program explains the need of virtual destructor,

#include <iostream>
#include <conio.h>
using namespace std;

class Base
{
   public:
      Base()
          { cout<<"Constructor: Base"<<endl;}
      ~Base()
          { cout<<"Destructor : Base"<<endl;}

};
class Derived: public Base
{     
   public:
       Derived()
              { cout<<"Constructor: Derived"<<endl;}
       ~Derived()
              { cout<<"Destructor : Derived"<<endl;}

};
void main()
{
    Base *Var = new Derived();      
    delete Var;
    _getch();       
}

In the above program you can see that the destrutor of the base class is not virtual and hence the output of the above program will be as follows,

Constructor: Base
Constructor: Derived
Destructor : Base

Destrutor of the derived object is not called in above case. Hence if you make the destructor of base class as virtual then the output will be as follows,

Constructor: Base
Constructor: Derived
Destructor : Derived
Destructor : Base


回答2:

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.



回答3:

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.



回答4:

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



标签: .net oop