What is a virtual destructor? Explain the use of it.
Page 1 of 1
What is a virtual destructor? Explain the use of it.
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
Similar topics
» When does a class need a virtual destructor?
» What is virtual function? Explain with an example
» What is Virtual base class? Explain its uses.
» What are pure virtual functions?
» What is virtual constructors/destructors?
» What is virtual function? Explain with an example
» What is Virtual base class? Explain its uses.
» What are pure virtual functions?
» What is virtual constructors/destructors?
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum