Virtual Destructor
Improve
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.
For example, the following program results in undefined behavior.
CPP
// CPP program without virtual destructor // causing undefined behavior#include <iostream>using namespace std;class base { public: base() { cout << "Constructing base\n"; } ~base() { cout<< "Destructing base\n"; } };class derived: public base { public: derived() { cout << "Constructing derived\n"; } ~derived() { cout << "Destructing derived\n"; }};int main(){ derived *d = new derived(); base *b = d; delete b; getchar(); return 0;} |
Output
Constructing base Constructing derived Destructing base
Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both base class and derived class destructors are called. For example,
CPP
// A program with virtual destructor#include <iostream>using namespace std;class base { public: base() { cout << "Constructing base\n"; } virtual ~base() { cout << "Destructing base\n"; } };class derived : public base { public: derived() { cout << "Constructing derived\n"; } ~derived() { cout << "Destructing derived\n"; }};int main(){ derived *d = new derived(); base *b = d; delete b; getchar(); return 0;} |
Output
Constructing base Constructing derived Destructing derived Destructing base
As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing). This way, you ensure against any surprises later.
Reference: Secure Coding
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Share your thoughts in the comments

