Loading....
Coupon Accepted Successfully!

 

Destructors And Virtual Functions

When a virtual function is invoked through a non-virtual member function, late binding is performed. When a virtual function is called through the destructor, the redefined function of a similar class is invoked. Consider the following program:
 

15.17 Write a program to call virtual function using destructors.

#include<iostream.h>

#include<conio.h>

class B

{

public:

~ B() {cout<<endl<<“ in virtual destructor”;}

virtual void joy() {cout<<endl<<“In joy of class B”;}

};

class D : public B

{

public :

~ D()

{

B *p;

p=this;

p->joy();

}

void joy() {cout<<endl<<“ in joy() of class D”;}

};

void main()

{

clrscr();

D X;

}

OUTPUT
in joy() of class D
in virtual destructor

Explanation:
In the above program, the destructor of the derived class function joy() is invoked. The member function joy() of the derived class is invoked followed by the virtual destructor.




Test Your Skills Now!
Take a Quiz now
Reviewer Name