🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #2501

Re: Virtual functions and destructors

#2501
From: John Max Skaller
Date: Fri, 10 Nov 1995 22:37
64 lines
2347 bytes
parker@WPI.EDU (Chris Parker) wrote:

>Does C++ require you to declare your destructor virtual whenever you declare
>any other member function in the class to be virtual?

  No. [The destructor will be virtual if and only if it is declared
  as such OR a destructor of a direct or indirect base is declared
  as such]

>Is it acceptable according to the standard 

  There is NO standard yet.

>for the destructor to be the only
>virtual member in the class?

  Yes.

>Is virtualness inherited by destructors?  

  As above. (Yes :-)

>
>If virtualness of destructors is inherited, then what is supposed to happen to
>in the case where one of our subclasses uses multiple inheritance and one 
>of the other trees leading to the subclass doesn't declare destructors to be 
>virtual anywhere?

  The derived class dtor is virtual.

   What happens if you delete an object of a derived
type via a pointer to a base for which the destructor is NOT
virtual is not defined. So don't do it :-)

  E.g. do NOT do:

  struct Base {};
  struct Derived : Base { int x; };
  Base *b = new Derived;
  delete b; // CRASH!!

Virtualness of the base dtor is required here to dispatch down to the
destructor of the most derived class, both to destroy the 
complete object AND to deallocate the correct memory extent. Eg:


  struct Base { virtual ~Base(){} };
  struct Derived : Base { int x; };
  Base *b = new Derived;
  delete b; // OK!!

-- 
John Max Skaller               voice: 61-2-566-2189
81 Glebe Point Rd              fax:   61-2-660-0850
GLEBE NSW 2037                 email: maxtal@suphys.physics.oz.au
AUSTRALIA                      email: skaller@maxtal.com.au



---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID: <480k5f$9lb@oznet03.ozemail.com.au>
Path: arc1-ca.pugleaf.net!128.32.155.1!matt
References: <47r71q$cp0@bigboote.WPI.EDU>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!128.32.155.1!matt
From: John Max Skaller <maxtal@suphys.physics.su.oz.au>
Newsgroups: comp.std.c++
Subject: Re: Virtual functions and destructors
Date: 10 Nov 1995 22:37:44 GMT
Organization: MAXTAL
Approved: matt@physics2.Berkeley.EDU (Matt Austern)
Message-ID: <480k5f$9lb@oznet03.ozemail.com.au>
References: <47r71q$cp0@bigboote.WPI.EDU>
NNTP-Posting-Host: physics2.berkeley.edu