The destructor of the derived class is not invoked when you pass a derived class object to a base class pointer. In this situation, by making the destructor of base class as virtual, you can invoke the destructors of both the base and derived classes, in the order, derived- to- base classes.
Listing 1 shows how to code a virtual destructor in a base class.
Listing 1: Creating a Virtual Destructor in a Base Class
#include<iostream.h>
#include<conio.h>
class Base
{
public:
Base()
{
cout<<"Constructor: Base"<<endl;
}
virtual ~Base()
{
cout<<Desrructor: Base" <<endl;
}
};
class Derived: public Base
{
public:
Derived()
{
cout<<"Constructor: Derived"<<endl;
}
~Derived()
{
cout<<"Destructor: Derived"<<endl;
}
};
void main()
{
Base *b = new Derived ();
delete b;
getch ();
}
OutPut::
Constructor: Base
Constructor: Derived
Destructor: Derived
Destructor: Base
You can declare a virtual destructor with an empty body, as shown in the following code snippet: virtual ~Base(){}
Listing 1 shows how to code a virtual destructor in a base class.
Listing 1: Creating a Virtual Destructor in a Base Class
#include<iostream.h>
class Base
{
public:
Base()
{
cout<<"Constructor: Base"<<endl;
}
virtual ~Base()
{
cout<<Desrructor: Base" <<endl;
}
};
class Derived: public Base
{
public:
Derived()
{
cout<<"Constructor: Derived"<<endl;
}
~Derived()
{
cout<<"Destructor: Derived"<<endl;
}
};
void main()
{
Base *b = new Derived ();
delete b;
getch ();
}
OutPut::
Constructor: Base
Constructor: Derived
Destructor: Derived
Destructor: Base
You can declare a virtual destructor with an empty body, as shown in the following code snippet: virtual ~Base(){}
No comments:
Post a Comment