Coupon Accepted Successfully!


Virtual Destructors

We have learned how to declare virtual functions. Likewise, destructors can be declared as virtual. The constructor cannot be virtual, as it requires information about the accurate type of the object in order to construct it properly. The virtual destructors are implemented in a similar manner to virtual functions. In constructors and destructors, pecking order (hierarchy) of base and derived classes is constructed. Destructors of derived and base classes are called when a derived class object addressed by the base class pointer is deleted.

For example, a derived class object is constructed using a new operator. The base class pointer object holds the address of the derived object. When the base class pointer is destructed using the delete operator, the destructor of the base and derived class is executed. The following program explains this:

15.16 Write a program to define virtual destructors.



class B



B() {cout<<endl<<“In constructor of class B”;}

virtual ~B() {cout<<endl<<“In destructor of class B”;}


class D: public B



D() {cout<<endl<<“In constructor of class D”;}

~ D() {cout<<endl<<“In destructor of class D”;}


void main()



B *p;

p= new D;

delete p;


In constructor of class B
In constructor of class D
In destructor of class D
In destructor of class B

In the above program, the destructor of the base class B is declared as virtual. A dynamic object is created, and the address of the nameless object that is created is assigned to pointer p. The new operator allocates the memory required for data members. When the object goes out of scope, it should be deleted, and the same should be performed by the statement delete p;. When the derived class object is pointed by the base class pointer object, in order to invoke the base class destructor, virtual destructors are useful.

Test Your Skills Now!
Take a Quiz now
Reviewer Name