TITLE: Why use virtual destructors (let me count the ways) PROBLEM: khan@San-Jose.ate.slb.com (Furqan Khan) How is the virtual destructor definition used in the case of an abstract class (class that cannot be instantitated directly). RESPONSE: rmartin@rcmcon.com (Robert Martin), 20 Sep 94 Folks: Using virtual destructors is very very important. You need an extremely good reason for not using one. There are three (count 'em, three) reasons to use virtual destructors. 1. Without a virtual destructor, the proper destructor may not be called: 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) may not 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, operator delete(void*) or operator delete (void*, size_t) may be called with the 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 is an abstract base or not. The same issues apply. So ALWAYS use a virtual 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 add 4 bytes to this for the vtbl pointer. If you are going to allocate a million of them, then you will have 2meg taken up by data, and 4meg taken up by pointers, that all point to the same thing. Thus, this is probably a good case for not declaring a virtual destructor.