FAQ 21.06 What is the purpose of a virtual destructor?

graphics/new_icon.gif

A virtual destructor causes the compiler to use dynamic binding when calling the destructor.

A destructor is called whenever an object is deleted, but there are some cases when the user code doesn't know which destructor should be called. For example, in the following situation, while compiling unawareOfDerived(Base*), the compiler doesn't even know that Derived exists, much less that the pointer base may actually be pointing at a Derived.

 #include <iostream> using namespace std; class Base { public:   ~Base() throw();                                   <-- 1 }; Base::~Base() throw() { cout << "Base destructor\n"; } void unawareOfDerived(Base* base) { delete base; } class Derived : public Base { public:   ~Derived() throw(); }; Derived::~Derived() throw() { cout << "Derived destructor\n"; } int main() {   Base* base = new Derived();   unawareOfDerived(base); } 

(1) Should be virtual but is not

Because Base::~Base() is nonvirtual, only Base::~Base() is executed and the Derived destructor will not run. This could be a very serious error, especially if the Derived destructor is supposed to release some precious resource such as closing a shared file or unlocking a semaphore.

The solution is to put the virtual keyword in front of Base's destructor. Once that is done, the compiler dynamically binds to the destructor, and thus the right destructor is always called:

 class Base { public:   virtual ~Base(); }; 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net