Destructor – Compiler Generated : always non-virtual

Share the Article

The compiler never generates a virtual destructor. Such destructors are always non-virtual. This is because C++ compiler cannot decide if in given architecture, the given class needs to become a base class or not. Therefore, in the absence of a “virtual” destructor in base class, the compiler shall not call corresponding function in derived class objects. Since, a non-virtual destructor of base class can not call virtual destructors in derived classes. Even when the given derived classes explicitly declare their destructors as virtual, then also the compiler shall not call them.


In this example, the MFBase class looks empty. This means it shall get compiler-generated destructor. (Actually, it shall get all other compiler-generated special functions- constructor, assignment operator also). However, the MFDerived class has an explicit “virtual” keyword. This generated special functions of MFBase is non-virtual, therefore, this shall never call destructor of MFDerived.

#include <iostream> //main header using namespace std; //namespace class MFBase { //Destructor is compiler-generated }; class MFDerived :public MFBase { public: MFDerived() { cout << "Derived Constructor" << endl; } virtual ~MFDerived() //virtual in derived class { cout << "Derived Destructor" << endl; } }; int main() { MFDerived *d1 = new MFDerived; MFDerived *d2 = new MFDerived; MFBase *b = d1; delete b; //Problematic delete d2; return 0; }

The compiler destroy the derived class part only in case of “d2”. The output of the program will be:

Derived Constructor //d1 (or b) Derived Constructor //d2 Derived Destructor //d1 (or b)

In case of “b”, clearly, the compiler destroys only the base class part, i.e. in MFBase class. The MFBase class compiler contains a compiler-generated destructor. Since, this is a “non-virtual” so it shall not call MFDerived. Please note that MFDerived class clearly has explicit virtual keyword.

Main Funda: If base class function is not having virtual keyword, then compiler will not consider it virtual with respect to derived class

Related Topics:

 What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How pointer to class members are different ?
What is reference collapsing?
How std::forward( ) works?
How std::move() function works?
Rule of Three
How delete keyword can be used to filter polymorphism

Share the Article

Leave a Reply

Your email address will not be published. Required fields are marked *