What is Virtual destructor? What is its use?
- If the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.
- Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.
class a
{
public:
a()
{
printf("\nBase Constructor\n");
}
~a()
{
printf("\nBase Destructor\n");
}
};
class b : public a
{
public:
b()
{
printf("\nDerived Constructor\n");
}
~b()
{
printf("\nDerived Destructor\n");
}
};
int main()
{
a* obj=new b;
delete obj;
return 0;
}
Output :Base Constructor
Derived Constructor
Base Destructor
By Changing~a()
{
printf("\nBase Destructor\n");
}
to
virtual ~a()
{
printf("\nBase Destructor\n");
}
Output :Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
What is virtual constructors/destructors?
Virtual destructors :- The explicit destroying of object with the use of delete operator to a base class pointer to the object is performed by the destructor of the base-class is invoked on that object.
- The above process can be simplified by declaring a virtual base class destructor.
- All the derived class destructors are made virtual in spite of having the same name as the base class destructor. In case the object in the hierarchy is destroyed explicitly by using delete operator to the base class pointer to a derived object, the appropriate destructor will be invoked.
Virtual constructor :A constructor of a class can not be virtual and if causes a syntax error.