Virtual Destructors

A destructor of a class is called every time an object goes out of scope or is deleted. Also, if a class is derived, all destructors will be called from the current class up to the most basic class. There’s a special case, when we have a pointer to a base class, but we instantiate an object of a derived class. See the example below, taken from [3].

// source: http://www.codersource.net/c/c-miscellaneous/c-virtual-destructors.aspx 
#include <iostream>
using namespace std;
class Base
{
public:
    Base(){ cout<<"Constructor: Base"<<endl;}
    ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
public:
    Derived(){ cout<<"Constructor: Derived"<<endl;}
    ~Derived(){ cout<<"Destructor : Derived"<<endl;}
};

int main( ){
    Base *Var = new Derived();
    delete Var;
    return 0;
}

In this case, only the destructor of the base class will be called (because of the pointer type). To make the destructor of the actual class to be called, we must declare the destructor as virtual. According to [1], if a base destructor is virtual, then all its descendants will have virtual destructors too. Hence, it’s enough to change the destructor declaration of the base class as follows:

...
    virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
....

The FAQ [1], also states a rule of thumb, strengthened by [2]:

make your destructor virtual if your class has any virtual functions

The reason behind this rule is that classes that have virtual function, will be probably derived and then it’s a good thing to protect against unexpected behavior. Furthermore, it’s said that you only “pay” to use virtual functions/destructors once per class. Since we already have a virtual function, a virtual destructor, in theory, would come for free.

References:
[1] http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7
[2] http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Inheritance#Inheritance
[3] http://www.codersource.net/c/c-miscellaneous/c-virtual-destructors.aspx

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s