Virtual Destructor in C++
As we have discussed, in C++ a destructor is generally used to deallocate memory and do some other cleanup for a class object and it’s class members whenever an object is destroyed. Destructor is distinguished by the tilde, the ‘~’ that appears in front of the destructor name.
In order to define a virtual destructor add the keyword virtual before the tilde symbol.
Need of Virtual Destructor? :
Virtual destructor is to destruct the resources in a proper order, when you delete a base class pointer pointing to derived class object.
Here are some points:
The destructor of base class can be virtual.
Whenever upcasting is done, destructor of base class must be declared virtual for proper destruction of the object.
Program without virtual destructor
#include<iostream> using namespace std; class Parent { int x; public: //Parent'sConstructor Parent() { cout<<"Parent's Constructor"; cout<< endl; } //Parent's Destructor ~ Parent() { cout<<"Parent's Desstructor"; cout<< endl; } }; class Child : public Parent { int y; public : //Child's Constructor Child() { cout<<"Child's Constructor"; cout<< endl; } //Child's Destructor ~Child() { cout<<"Child's Constructor"; cout<< endl; } }; int main() { //Upcasting(implicit) Parent *p = new Child() ; delete (p); return 0; }OUTPUT:
Parent's Constructor Child's Constructor Parent's Destructor
As you can notice in the above example Child's Destructor is not invoking, means proper destruction of objects is not happening. For proper destruction of object you need to make base class destructor as virtual.
Program with virtual destructor
#include<iostream> using namespace std; class Parent { int x; public: //Parent'sConstructor Parent() { cout<<"Parent's Constructor"; cout<< endl; } //Parent's Destructor virtual ~ Parent() { cout<<"Parent's Desstructor"; cout<< endl; } }; class Child : public Parent { int y; public : //Child's Constructor Child() { cout<<"Child's Constructor"; cout<< endl; } //Child's Destructor ~Child() { cout<<"Child's Constructor"; cout<< endl; } }; int main() { //Upcasting(implicit) Parent *p = new Child() ; delete (p); return 0; }OUTPUT:
Parent's Constructor Child's Constructor Child's Destructor Parent's Destructor
Note that the derived class destructor will be called before the base class.
So, now you’ve seen why we need virtual destructors and also how they work.
Note:
Constructors are never virtual, only destructor can be virtual.
Next topic is this pointer
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at info@prowessapps.in
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at info@prowessapps.in