Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!hplabs!hp-pcd!hplsla!jima From: jima@hplsla.HP.COM (Jim Adcock) Newsgroups: comp.lang.c++ Subject: Re: Virtual destructors - why aren't they all? Message-ID: <6590296@hplsla.HP.COM> Date: 11 Oct 89 21:36:28 GMT References: <10627@csli.Stanford.EDU> Organization: HP Lake Stevens, WA Lines: 21 >keith@csli.Stanford.EDU (Keith Nishihara) / 5:55 pm Oct 10, 1989 / >I was surprised to discover that calling delete on a derived class >object pointed to by a pointer to the base class failed to call >the derived class destructor. (cfront 1.2) (See example below.) >I cannot think of any case where this would be the desirable behaviour. >Fortunately, it appears that declaring the destructor virtual causes >the appropriate behaviour to happen. Why are not all desctructors >virtual? Is this true in other C++ systems? Well, one answer is that declaring a function virtual causes both a space penalty in an object of that class [said penalty constant as long as one or more virtual functions are declared] and also a time penalty in invoking that virtual function. Presumably, if someone gives you a class with a non-virtual destructor and you'd rather have a virtual destructor, then you can trivially derive a new class that has a virtual destructor. But you can't go the other way. Once a superclass declares a virtual function subclasses always get to eat the space and/or time penalties. This behavior is true of all C++ I have seen. If you want a function to be virtual, declare it virtual. This requirement also has the advantage of language consistency.