Confused? Here's a simplified rule of thumb that usually protects you and usually doesn't cost you anything: make your destructor virtual if your class has anyvirtual functions. Rationale:
that usually protects you because most base classes have at least one virtual function.
that usually doesn't cost you anything because there is no added per-object space-cost for the second or subsequent virtual in your class. In other words you've already paid all the per-object space-cost that you'll ever pay once you add the first virtual function so the virtual destructor doesn't add any additional per-object space cost. (Everything in this bullet is theoretically compiler-specific but in practice it will be valid on almost all compilers.)
Its always better to have a virtual destuctor in a class which has got virtual functions.When an object is created with instantiating the derived class like [baseclass* bclass new derivedclass] when you delete the base class pointer it calls the derived calss destructor also so it leaves no chance for memory leak.
Its always better to have a virtual destuctor in a class which has got virtual functions.When an object is created with instantiating the derived class like [baseclass* bclass new derivedclass] when you delete the base class pointer it calls the derived calss destructor also so it leaves no chance for memory leak.
virtual destructor is very useful....everyone should use that......if there is no any strong reason for not using virtual destructor....like...One class having two char variable...........so it's size is two byte........if u use virtual destructor it's size will be 6 bytes....4 byte for virtual ptr....Now if this class have 1 millions objects...so 4 magabyte memory will be lost...where all ptr do the same thing.....
really when we delete an object through base class pointer at that time virtual destrocter most for virtual function for order base des-derived-des for avid memory leakbut its depend upon u when u delete the object through derived class object its depend upon usearmost of thing is that dep. upon user........
these are the following 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!!!