PDA

View Full Version : virtually destructive


kmj
04-01-2002, 06:53 PM
always make sure your parent classes have virtual destructors.... stupid memory leaks.

(c:

sans-hubris
04-01-2002, 09:11 PM
Ahh, yes, very true.

Dru Lee Parsec
04-02-2002, 08:09 PM
Since virtual destructors are so important and useful, I wonder why the compiler doesn't make all destructors virtual?

I mean, can you think of an example where you wouldn't want the destructor to call it's parent's destructors first?

I guess if the parent classes didn't do any memory assignment then not using a virtual destructor may be an optimization choice. But it sure seems like a "virtual destructor" is the behavior that all destructors should have.

kmj
04-02-2002, 09:40 PM
Actually, the issue is more that the program thinks you have an instance of Parent, because you made a pointer to Parent. Actually you have an instance of Child, because that's how you allocated it. Now, Child's destructor may be all set an written perfectly, and virtual... but if Parent doesn't have a virtual destructor explicitly declared/defined (even if it's empty), then when you delete the Parent*, the Parent* destructor gets called (which defaults to nothing) but not the child destructor. And therein lies the memory leak. (I love that phrase, "and therein lies...")

I thought (and voiced) the same thing as you, though... Why on earth not do it by default, just in case? The answer I got from someone who's opinions on such matters I generally find sound: "Well, there are some classes (for example, MFC CStrings or our internal DStrings which mimic CString functionality/performance) for which that extra DWORD would be unwanted. Some classes just have to be tremendously lightweight." I guess it makes sense to me, maybe it's too difficult to make the compiler smart enough to know if a virtual destructor is needed for a given class... not likely, given the whole dynamic point of inheritence... but to be honest I'm too lazy to give the subject the thought it deserves right now. :)