When can we use the virtual destructors ?


Consider a situation where a derived class object is created using new. The address of this object can be assigned to a pointer to a base class object. Now if we delete the pointer, since the pointer is a base class pointer this would result in a call to the base class destructor. Ideally, firstly the derived class destructor should be called followed by the base class destructor. This can be ensured by using a virtual destructor in the base class. The following program shows how this can be implemented.

#include <iostream.h>

class base

{

public :

base( )

{

cout << endl << “In base class constructor” ;

}

virtual ~base( )

{

cout << endl << “In base class destructor” ;

}

} ;

class derived : public base

{

public :

derived( )

{

cout << endl << “In derived class constructor” ;

}

~derived( )

{

cout << endl << “In derived class destructor” ;

}

} ;

void main( )

{

base *b ;

b = new derived ;

delete b ;

}

This entry was posted in C++ and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>