# Can't delete

## Recommended Posts

Android07    122
I'm having some problems with the destructors for my program. I have a Product class that has several different class inheriting from it. These all get destructed fine when they should except for object of one particular type that inherits from Product. When it should be deleted I get an assertion failure at the line _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)); in dbgdel.cpp The object is of type CreditCard that also inherits from Card. Neither Card or CreditCard has a destructor as they don't allocate any resources, only the Product class. I don't know if the multiple inheritance has anything to do with this as I have never used it before. Product *cc = new CreditCard(); delete cc; causes the error but CreditCard *cc = new CreditCard(); delete cc; works fine. Is there anyway that I can fix this or am I going to have to cast by Product pointer to a CreditCard pointer before I can delete it? Thanks.

##### Share on other sites
rip-off    10979
Does Product have a virtual destructor?

Are you saying that this fails:
#include "creditcard.h"int main(){    Product *cc = new CreditCard();    delete cc;}

##### Share on other sites
Android07    122
Yes, that fails, and no. Product doesn't have a virtual constructor.

##### Share on other sites
rip-off    10979
Can you post the particular classes (Product and CreditCard)?

Classes you want to delete through a pointer to the base class should have a virtual destructor. In general, if you have any virtual functions in a class it should have a virtual destructor.

Finally, are you sure it makes sense for a CreditCard to be a subclass of Product? Maybe it does in your program (if you are modelling a bank or something) but intuitively these concepts are distinct. I mention this because some programmers overuse inheritance in cases where it isn't appropriate.

##### Share on other sites
bobofjoe    322
Well, it should. Without a virtual destructor, bad things will happen when you attempt to delete a CreditCard instance from a Product pointer.

##### Share on other sites
Android07    122
It is for banking application, I just tried a virtual destructor and it works now.

Thanks for the help. I have never seen anywhere that you should have a virtual destructor for class with virtual functions so I never thought to do that.

Thanks again.

##### Share on other sites
rip-off    10979

That entire site is pure gold - bookmark it.

##### Share on other sites
the_edd    2109
Quote:
 Original post by Android07Thanks for the help. I have never seen anywhere that you should have a virtual destructor for class with virtual functions so I never thought to do that.

*Any* book will tell you this. If yours doesn't, get a different one.