VOOZH about

URL: https://www.geeksforgeeks.org/cpp/virtual-destructor/

⇱ Virtual Destructor - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Virtual Destructor

Last Updated : 23 Jul, 2025

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. 


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, 


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 
 

Comment
Article Tags: