[LC++]STL Iterators and integers

Grzegorz Mazur mazur at chemia.uj.edu.pl
Fri Aug 10 18:06:05 UTC 2001


Hi,

On Thu, 9 Aug 2001, Chris Vine wrote:

> I know I am going against fashion, but I have never really thought that was a 
> good reason for not deriving from the STL container classes.  If you are 
> addressing an object of a non-polymorphic class through a base class pointer, 
> your program will be in trouble long before you reach the destructor.  You 
> will have been calling the wrong methods for the class from the outset.
> 
> The fact that deleting it by means of a base class pointer will give 
> undefined behaviour will be the least of your worries.  (And of course, if 
> the object is constructed on the stack rather than the heap, correct 
> destruction is guaranteed in any event -- but the program will still give the 
> wrong results).

I hate to support politically correct and fahionable point of view, but in
this case I have to do so. I try to put it simple: the difference is that
destructor will be called always, for any object which was created, and
even worse, the destructor is called implicitly, so your only hope is that
compiler generated code which selects the right one. And if a class you
derive from doesn't have virtual destructor, you create a perfect
opportunity for very subtle and hard to track down errors. (The fact, that
it works correctly when allocated on stack and fails when allocated on
heap doesn't IMHO really help.)

Another way to explain it is following. If you try to override a member
function which is not virtual and then call it through a pointer to base
class, the behaviour can (and will) be different from what you would
(wrongly) expect, but is well-defined. If you make the same mistake with
destructor, you have undefined behaviour at the first place where delete
with pointer to base class is called. 

Regards,
--
Grzesiek




More information about the tuxCPProgramming mailing list