Deleting a derived class object using a pointer to a base class 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, following program results in undefined behavior.
Although the output of following program may be different on different compilers, when compiled using Dev-CPP, it prints following:
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,
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
This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Pure virtual destructor in C++
- Calling virtual methods in constructor/destructor in C++
- Private Destructor
- Difference Between Constructor and Destructor in C++
- Order of Constructor/ Destructor Call in C++
- Is it possible to call constructor and destructor explicitly?
- What happens when a virtual function is called inside a non-virtual function in C++
- Difference between Virtual function and Pure virtual function in C++
- __attribute__((constructor)) and __attribute__((destructor)) syntaxes in C
- Virtual Function in C++
- Virtual base class in C++
- Can virtual functions be inlined?
- Can virtual functions be private in C++?
- Advanced C++ | Virtual Constructor
- Can static functions be virtual in C++?
- Virtual destruction using shared_ptr in C++
- Virtual functions in derived classes
- Default arguments and virtual function
- Advanced C++ | Virtual Copy Constructor
- Pure Virtual Functions and Abstract Classes in C++