GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Tech FAQs  >  OOPS
Go To First  |  Previous Question  |  Next Question 
 OOPS  |  Question 210 of 258    Print  
Why we use Virtual Destructor?

  
Total Answers and Comments: 13 Last Update: June 10, 2009     Asked by: varshakumbhar 
  
 Sponsored Links

 
 Best Rated Answer
Submitted by: Faheem Arshad
 

A difference between a destructor (of course also the constructor) and other member functions is that, if a regular member function has a body at the derived class, only the version at Derived class gets executed. Whereas in case of destructors, both derived as well as base class versions get executed.

Now turning our attention to why a destructor has to be virtual, the reason is that we, programmers are very smart. We'll do days and nights of work to inherit and extend the functionality of an existing class which is being used, and say that we don't want to change the implementation/interface just for the sake of a new entrant. Let me explain this with an example.


#include <iostream.h>
class Base
{
       public:
          Base(){ cout<<"Constructor: Base"<<endl;}
          ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
     //Doing a lot of jobs by extending the functionality
       public:
           Derived(){ cout<<"Constructor: Derived"<<endl;}
           ~Derived(){ cout<<"Destructor : Derived"<<endl;}
> };
void main()
{
        Base *Var = new Derived();
        delete Var;
}

Try executing this code, you'll see the difference. To our observation, the constructors are getting called in the proper order. But to the dread of a programmer of a large project, the destructor of the derived class was not called at all.

This is where the virtual mechanism comes into our rescue. By making the Base class Destructor virtual, both the destructors will be called in order. The following is the corrected sample.

#include <iostream.h>
class Base
{
       public:
          Base(){ cout<<"Constructor: Base"<<endl;}
          virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
     //Doing a lot of jobs by extending the functionality
       public:
           Derived(){ cout<<"Constructor: Derived"<<endl;}
           ~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
void main()
{
        Base *Var = new Derived();
        delete Var;
}

Note:
There is one more point to be noted regarding virtual destructor. We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.



Above answer was rated as good by the following members:
Amicable
  Sorting Options  
  Page 1 of 2   « First    1    2    >     Last »  
January 03, 2006 21:07:36   #1  
Nitin Gupta        

RE: Why we use Virtual Destructor?
virtual destructor is used so that while deleting the pointer to a base class but pointing to a base class invokes the Derived classes destructor first then the base classes destrcutore. Hence preventing a memory leak.
 
Is this answer useful? Yes | No
January 19, 2006 05:09:03   #2  
samiksc Member Since: October 2005   Contribution: 233    

RE: Why we use Virtual Destructor?

The virtual destructor has the same purpose as a virtual function. At runtime looking at the type of object referred by a pointer or reference it is decided which destructor to call -- the destructor of the base class or the destructor of the derived class.

For example suppose B is a base class and D is a class derived from B and suppose both classes have declared their destrcutor as virtual. Suppose a pointer B *ptr is initialized as follows:

B *ptr new D();

Now the ptr is of type B* but points to an object of D. So when this object is freed or goes out of scope D's destructor will be called since the destructors have been declared as virtual.


 
Is this answer useful? Yes | No
March 21, 2006 01:59:32   #3  
Shailesh_Pandey Member Since: March 2006   Contribution: 2    

RE: Why we use Virtual Destructor?

Your understanding made things simpler.


 
Is this answer useful? Yes | No
March 29, 2006 04:56:13   #4  
dharmaraj.guru Member Since: March 2006   Contribution: 3    

RE: Why we use Virtual Destructor?
Ref: http://cpptips.hyperformix.com/cpptips/why_virt_dtorFolks: Using virtual destructors is very very important. You need anextremely good reason for not using one.There are three reasons to use virtual destructors.1. Without a virtual destructor the proper destructor may not becalled:struct B {~B();};struct D : B {~D();};B* b new D;delete b; // <--------- Will not call D::~D() !!!!!2. Without a virtual destructor operator delete(void* size_t) maynot be called with the correct size.struct B {~B(); operator delete(void* size_t);};struct D : B {~D();};B* b new D;delete b; // <--------- Will call operator delete(void* size_t) with // the size of B not the size of D!!!3. Without a virtual destructor and when MI is used operatordelete(void*) or operator delete (void* size_t) may be called withthe wrong address.struct B {~B();};struct A {};struct D : A B {~D();};B* b new D;delete b; // <--------- May not pass to operator delete the address // that was returned by operator new!!!All of these conditions are very deadly. It does not matter if B isan abstract base or not. The same issues apply. So ALWAYS use avirtual destructor unless you have a very very good reason.What is a good reason? Well you have a class like: struct TinyPoint { char x y; };This class takes up two bytes. A virtual destructor will probably add4 bytes to this for the vtbl pointer. If you are going to allocate amillion of them then you will have 2meg taken up by data and 4megtaken up by pointers that all point to the same thing. Thus this isprobably a good case for not declaring a virtual destructor.
 
Is this answer useful? Yes | NoAnswer is useful 1   Answer is not useful 0Overall Rating: +1    
May 05, 2006 01:24:27   #5  
narendra kumar        

RE: Why we use Virtual Destructor?

thanx nitin gupta

is there any real time example towords this virtual destructor. please send me.

really i got the whole concept of virtual destructor.


 
Is this answer useful? Yes | No
July 11, 2006 07:07:24   #6  
Suganthi        

RE: Why we use Virtual Destructor?

A very good explaination.

Thx.


 
Is this answer useful? Yes | No
July 11, 2006 07:21:55   #7  
Suganthi        

RE: Why we use Virtual Destructor?
excellent
 
Is this answer useful? Yes | No
January 09, 2007 08:45:58   #8  
muralidhar        

RE: Why we use Virtual Destructor?
Hello all.

This is the simple example code..

#include <iostream>
using namespace std;
class Base
{
public:
Base(){ cout<< Constructor: Base <<endl;}
virtual ~Base(){ cout<< Destructor : Base <<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<< Constructor: Derived <<endl;}
~Derived(){ cout<< Destructor : Derived <<endl;}
};
void main()
{
Base *Var new Derived();
delete Var;
}

 
Is this answer useful? Yes | No
March 15, 2007 06:52:52   #9  
Faheem Arshad        

RE: Why we use Virtual Destructor?

A difference between a destructor (of course also the constructor) and other member functions is that if a regular member function has a body at the derived class only the version at Derived class gets executed. Whereas in case of destructors both derived as well as base class versions get executed.

Now turning our attention to why a destructor has to be virtual the reason is that we programmers are very smart. We'll do days and nights of work to inherit and extend the functionality of an existing class which is being used and say that we don't want to change the implementation/interface just for the sake of a new entrant. Let me explain this with an example.


#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<<endl;}
~Derived(){ cout<<"Destructor : Derived"<<endl;}
> };
void main()
{
Base *Var new Derived();
delete Var;
}

Try executing this code you'll see the difference. To our observation the constructors are getting called in the proper order. But to the dread of a programmer of a large project the destructor of the derived class was not called at all.

This is where the virtual mechanism comes into our rescue. By making the Base class Destructor virtual both the destructors will be called in order. The following is the corrected sample.

#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<<endl;}
~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
void main()
{
Base *Var new Derived();
delete Var;
}

Note:
There is one more point to be noted regarding virtual destructor. We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure it will have to implement an empty body (at least) for the destructor.


 
Is this answer useful? Yes | NoAnswer is useful 1   Answer is not useful 0Overall Rating: +1    
July 04, 2007 01:23:05   #10  
vineet        

RE: Why we use Virtual Destructor?

We can declare pure virtual destructor but need to specify its body.
Class Base
{
~Base() 0;
}

Base::~Base(){}

Pure virtual destructor does the same thing which other virtual functions do makes Base class abstract.
I didn't find any other reason to make virtual destructor pure....
does any body knows???

regards
Vineet


 
Is this answer useful? Yes | No
  Page 1 of 2   « First    1    2    >     Last »  


 
Go To Top


 Sponsored Links

 
About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape