TITLE: destruction through base pointers with no virtualness [ this picks up on a thread about virtual destructors and what bad things can happen if they are not present in a design. -adc ] RCM = rmartin@oma.com (Robert C. Martin), 20 Jan 96 MN = neeri@iis.ee.ethz.ch (Matthias Neeracher) RCM: class X {}; // no virtual functions, no virtual destructor; class Y {}; // no virtual functions, no virtual destructor; class Z : public X, public Y {}; X* xp = new Z; delete xp; // undefined behavior. Probable heap corruption followed // by crash several million instructions later. MN: I have two objections to this example: a) While I have learned since my posting that this behavior is indeed undefined by the Draft standard, I wouldn't go as far as saying that heap corruption is "probable". It seems to me that all compilers which implement new/delete with malloc/free (and most compilers I work with seem to do this) will not corrupt the heap. RCM: If we express the above in terms of malloc and free, the result will be roughly equivalent to this: char* p = malloc(sizeof(X) + sizeof(Y)); free(p + sizeof(Y)); This will corrupt the majority of heap managers out there. MN: What I was trying to point out in my article was that there was no legitimate use I could think of (suggestions are welcome, of course) for accessing classes without virtual functions through pointers to their bases. RCM: When Client A needs Service X, and Class B needs Service Y, and yet both can be supported in the same object Z, it is tempting, and rewarding to create the structure above. I agree that virtual functions will normally be used to communicate between the two branches. But I have often run accross cases where the only communication took place in the constructor of Z; and that no virtual functions were necessary.