Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: All
Jul 17, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
  ~A() // non virtual
  // ...

 class B: public A{ // bad; inheriting a non virtual dtor
  // ...

 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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date