GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Tech FAQs  >  OOPS

 Print  |  
Question:  Why we use Virtual Destructor?



March 03, 2006 04:56:13 #4
 Dharmaraj G   Member Since: March 2006    Total Comments: 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.
     

 

Back To Question