//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