devxlogo

What’s Wrong with Inheriting from a Class that Has no Virtual Destructor?

What’s Wrong with Inheriting from a Class that Has no Virtual Destructor?

Classes having a non-virtual destructor aren’t meant to be derived from (such classes are usually known as “concrete classes”). std::string, std::complex, and all STL containers are concrete classes. Why is inheriting from such classes not recommended? When you use public inheritance, you create an is-a relationship between the base class and the derived class. Consequently, pointers and references to base can actually point to a derived object. However, because the destructor isn’t virtual, C++ will not call the entire destructor chain when you delete such an object. Foe example:

 class A { public:  ~A() // non virtual  {  // ...  } }; class B: public A{ // bad; inheriting a non virtual dtor public:  ~B()  {  // ...  } }; int main() { A * p = new B; // seemingly OK delete p; // oops, B's dtor not called! }

The result of failing to invoke an object’s destructor is undefined behavior. Therefore, you shouldn’t use publicly inherit from concrete classes.

devx-admin

Share the Post: