dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

WEBINAR:

On-Demand

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
 {
 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.

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