3.2.5. Virtual Destructors
Q24. Write a note on virtual destructors.
Answer:
Virtual Destructor
Virtual destructor is created by placing virtual keyword before a destructor. Its implementation is similar to the implementation of virtual constructors. The hierarchy of base and derived classes are created in constructors and destructors. From this hierarchy, derived and base class object reference by base class pointer when a derived class object is constructed using a new operator, It's address is stored in base class pointer object. This base class pointer object is destructed by using delete operator by invoking this operator.
Program
Answer:
Virtual Destructor
Virtual destructor is created by placing virtual keyword before a destructor. Its implementation is similar to the implementation of virtual constructors. The hierarchy of base and derived classes are created in constructors and destructors. From this hierarchy, derived and base class object reference by base class pointer when a derived class object is constructed using a new operator, It's address is stored in base class pointer object. This base class pointer object is destructed by using delete operator by invoking this operator.
Program
#include<conio.h>
#include<iostream.h> .
class P
{
public:
P()
{
cout<<endl<<‘“ClassP
constructor”;
}
virtual ~P()
{
cout<<endl<<ClassP
destructor’;
}
};
class Q : public P
{
public:
Q()
{
cout<<endl<<“ClassQ
constructor”;
}
~Q()
{
cout<<endl<<“ClassQ
destructor”;
}
};
void main()
{
clrscr();
P*ptr;
ptr=new Q;
delete ptr;
getch();
}
Output