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.

See also  11 Effective Keyword Research Tools and Techniques

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist