Monday, August 17, 2009

memory leak with inheritance and destructors

I use inheritance and virtual functions fairly frequently, but I am wondering how common this is:

A little bit of context -

When using inheritance, destructors are called in the reverse order of inheritance. If a base class pointer points to a derived class object, and later we use the delete operator to delete the object, then the derived class destructor is not called. Refer to the code that follows:



#include
class base
{
public:
~base()
{

}
};

class derived : public base
{
public:
~derived()
{

}
};

void main()
{

base *ptr = new derived();
// some code
delete ptr;
}

The result is a memory leak.

Solution to avoid this -

Make the destructor virtual in the base class. A virtual destructor is one that is declared as virtual in the base class.



#include
class base
{
public:
virtual ~base()
{

}
};

class derived : public base
{
public:
~derived()
{

}

};

void main()
{

base *ptr = new derived();
// some code
delete ptr;
}


Does this mean when using virtual functions, it is always a good idea have the destructor virtual as well?

No comments: