Monday 29 June 2009

The case for 'virtual destructor'

You may often find that the destructor of your class is virtual. The main reason for having virtual destructor stems from the fact that some other class may derive from your class. If the derived object is referenced as base object and destroyed then the derived class objects wont be deleted. To overcome this problem we define the destructor virtual . Lets look at an example:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing the need for Virtual Destructor
#include <iostream>

using namespace
std;

class
Base
{

public
:
Base() {
cout<<"Base Constructor Called"<<endl;
}
~
Base() {
cout<<"Base Destructor Called"<<endl;
}
};


class
Derived : public Base
{

public
:
Derived() {
cout<<"Derived Constructor Called"<<endl;
}
~
Derived() {
cout<<"Derived Destructor Called"<<endl;
}
};


int
main()
{

cout<<"\nTESTING NON-VIRTUAL BASE DESTRUCTOR\n";
Base *b = new (Derived);
delete
(b);
return
0;
}


The output is as follows:

Now lets modify the base destructor to make it virtual.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing the need for Virtual Destructor
#include <iostream>

using namespace
std;

class
Base
{

public
:
Base() {
cout<<"Base Constructor Called"<<endl;
}

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


class
Derived : public Base
{

public
:
Derived() {
cout<<"Derived Constructor Called"<<endl;
}
~
Derived() {
cout<<"Derived Destructor Called"<<endl;
}
};


int
main()
{

cout<<"\nTESTING VIRTUAL BASE DESTRUCTOR\n";
Base *b = new (Derived);
delete
(b);
return
0;
}



The modified output is as follows:


There is one more point to be noted regarding virtual destructor. We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.

You can read more about this at C++ FAQ.

No comments:

Post a Comment