Inheritance- III


The following topics are covered in this section:


Can a Destructor be Virtual?

We’ve seen about classes and we’ve also dealt with inheritance. But there is one case that we haven’t seen as yet. Let’s go back to the class called ‘car’ and let’s assume that we have one derived class from ‘car’ called ‘ferrari’. If you create an instance of ferrari, then when the ferrari object is destroyed this will invoke 2 destructors (the ‘ferrari’ class destructor and the ‘car’ class destructor).

Suppose we create an object of ‘ferrari’ using the ‘new’ operator and the pointer is of the base class’ type (i.e. the pointer is of type ‘car’). What do you think will happen? Just see the coding below so that you get an idea of the problem:

#include <iostream.h>
class car
{private:
    int speed;
    char color[20];
public:
~car( )
{
cout<<"\nDestroying the Car";
}
};
class ferrari:public car
{public:
ferrari( )
{
cout<<"Creating a Ferrari";
}
~ferrari( )
{
cout<<"\nDestroying the Ferrari";
}
};
int main( )
{car *p = new ferrari;
delete p;
return 0;
}

You can be sure that a new ferrari object has been created. The question is: does the ferrari object really get destroyed?

The output for the above program would be:

Creating a Ferrar
Destroying the Car

Surprised? The ferrari object hasn’t been destroyed though the object was created. The problem is that since we are using a pointer to the base class the compiler tends to only invoke the base destructor when you delete it. How to overcome this problem? This is where we have to make the destructor virtual. By making the destructor virtual, the correct destructor will be called in the program. A destructor is just like any other member function; so to make it virtual just precede the base class destructor by the keyword ‘virtual’. Check out this modified program:

class car
{private:
    int speed;
    char color[20];
public:
virtual ~car( )
{
cout<<"\nDestroying the Car";
}
};
class ferrari:public car
{public:
ferrari( )
{
cout<<"Creating a Ferrari";
}
~ferrari( )
{
cout<<"\nDestroying the Ferrari";
}
};
int main( )
{ car *p = new ferrari;
delete p;
return 0;
}

The output would now be:

Creating a Ferrari
Destroying the Ferrari
Destroying the Car

This is what we call virtual destructor in C++.


Pointers to base and derived classes

Please go to the new website to see revised content - all updates will happen only there; it's difficult to maintain two versions!

Copyright © 2004 Sethu Subramanian All rights reserved.