Re: virtual destructor revisted

From: John Harrison (john_andronicus_at_hotmail.com)
Date: 06/20/04


Date: Sun, 20 Jun 2004 06:36:18 +0100


"ctick" <ctick@flare.com> wrote in message
news:bZ8Bc.7621$OB3.2639@bgtnsc05-news.ops.worldnet.att.net...
> A reason for declaring a "virtual destructor" for a Base class is to make
> sure the destructor of Derived class will be invoked when a pointer of
Base
> type is used to delete an object of Derived.
>
> Is this the only reason to define "virtual destructor" for a Base class?

Pretty much yes. There is one other rather obscure reason. It might be that
you want class Base to have at least one virtual function (so that you can
use dynamic_cast on it for instance) but you don't have any other suitable
method to declare as virtual.

>
> Since it's always possible that users of any Base class will delete a
> Derived object like that, does this mean that a "virtual destructor" is
> always necessary?

Not really. There is an overhead to using virtual functions. If your class
is not intended to be used polymorphically then don't use any virtual
functions (including destructor) and document that fact. Unfortunately its
always possible that users will do something stupid.

john



Relevant Pages

  • Re: COMPILE!
    ... > There's your problem - calling a virtual function from a destructor ... Calling a pure virtual function ... > from a destructor causes undefined behaviour (and fortunately VC seems ... > one in the most derived class. ...
    (comp.lang.cpp)
  • Re: Is it good practice for a function to return data?
    ... Another would be for the LOS data to be stored in a separate class of ... >> virtual function that handles processing the output. ... >> class can specify how the output will be processed by overloading that ... derived class might process a file by deleting it, ...
    (comp.lang.cpp)
  • Re: Inheriting from STL bitset
    ... > baseclass destructor explicitly in my derived class? ... Virtual destructor is needed when you delete an object ... of derived class using a base class pointer. ...
    (comp.lang.cpp)
  • Re: function lookup
    ... and derived class member share the same name but are otherwise unrelated. ... The wrong overload can kick in. ... to prevent overriding a virtual function, which means you must check all ... inadvertently overriding a virtual function. ...
    (microsoft.public.vc.language)
  • Re: Number of Vtables in derived:base class
    ... having virtual function a Vtable will be created to that class". ... class CommandButton: public Window ... Now I would like know does for derived class "CommandButton" another ...
    (microsoft.public.vc.language)