Posted by William D McQuain on December 18, 2001 at 14:50:00:
In Reply to: Why destuctor should be virtual posted by Tim on December 18, 2001 at 14:38:25:
: Just want to make sure about it before the exam.
: Thanks for any advice
Suppose you have an inheritance hierarchy, say class D derived from class B, and suppose that the class D allocates some memory dynamically that class B does not (e.g., class D adds a data member that's a pointer to a dynamically-allocated array, and the class D constructors will take care of setting up that array).
Now, the destructor for class B knows nothing about this memory, so it won't deallocate it.
When an object of class D is destroyed, you desparately need for the D::~D() to be invoked, not just for B::~B() to be invoked.
But, if you're accessing your class D object via a B* (as you would in a polymorphic situation), then D::~D() won't be invoked unless runtime binding is used, and that won't happen unless B::~B() is virtual.
This is probably one of the more common errors C++ programmers make.
Post a Followup