Re: Polymorphism

From: James Dennett (jdennett_at_acm.org)
Date: 12/11/04


Date: Sat, 11 Dec 2004 10:17:13 -0800

B. v Ingen Schenau wrote:

> Rich wrote:
>
>
>>Hello,
>>
>>I am intrigued by this post and the program :)
>>
>>I have not really got as far as polymorphism yet, but a google says
>>something about setting the base class destructor as virtual as well
>>and then also making derived classes destructors virtual
>>
>>something to do with making the whole chain of destructors being
>>called.
>>
>>So I am thinking that if the Base class destructor is not made virtual
>>then when delete is called it won't call the derived classes
>>destructor but it's own one instead?
>
>
> Yes, that is what typically will happen.
> Officially it is undefined behaviour, so anything could happen.

A long time ago I posted an example of an inheritance hierarchy
in which omitting the "virtual" keyword from a destructor would
give a crash on all the systems on which I tested it; this is
not just a theoretical problem. That said, if you stick to
single inheritance, and common compilers, then you'll probably
just get a call to the wrong destructor.

-- James



Relevant Pages

  • Re: How to override destructor?
    ... I am attempting to override the destructor ... class CLeadsBrowser ... // I wish to add some cleanup code here ... Base class destructor will be called ...
    (microsoft.public.vc.language)
  • Re: inhibit compiler warning C4624 for a class hierarchy
    ... Additionally the destructors of all derived classes should ... a public destructor, instances of that class could be ... created on the "stack" without error or even a warning. ...
    (microsoft.public.vc.language)
  • Re: replicated base classes
    ... destructor in a base class if there's derived classes. ... then the derived classes does not warrant virtuals. ... > class A constructor ...
    (alt.comp.lang.learn.c-cpp)
  • Re: base class virtual destructor not resolving inherited virtual functions
    ... an object of "CChild", work with it, and then delete it. ... destructor, which does nothing, and then calls the CBase ... calls a virtual function which is overridden in CChild -- BUT, ... versions overridden by derived classes, ...
    (microsoft.public.vc.mfc)