Virenk's Blog

C++ – Don’t forget to make destructors virtual!

Posted on: September 21, 2010

Recently i was debugging a case taking a large amount of memory.  Reason : memory was not freed for some classes which had not been defined with virtual destructors.

While deriving a class from another class, it is important to make destructor of parent class virtual.

Consider following scenario:

class A
string sa;
A(string sia);
// ~A();
virtual ~A(); // needed else there will be memory leak


class B: public A
string sb;
B(string sia, string sib);


A::A(string sia):sa(sia)

B::B( string sia, string sib):A(sia),sb(sib)
A::~A() {
cout << “destroying A ” << endl;
B::~B() {
cout << “destroying B ” << endl;

int main(int argc, char*argv[])
string param1=”abcd”;
string param2=”efgh”;
A *b;
b = new B(param1, param2);
delete b; // memory leak if A does not have virtual destructor

B* b1 = new B(param1, param2);
delete b1; //this will automaticall call A’s destructor
return 0;

In above scenario, if A’s destructor is not defined as virtual,  “delete b” will  call destructor of A, as it is pointing to object of type A, so contents of B will not be deleted.

If you run valgrind (tool for debugging memory leaks) you will find memory leak for std::string::_Rep::_S_create.

Make sure of above else expect a lot of memory leaks in your program!. 😛



Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s


  • None


%d bloggers like this: