Virtual destructor question 
Author Message
 Virtual destructor question


Quote:
> Suppose I have some code like the following:
> class Base {};
> class Derived : public Base {};

> Base *p = new Derived;
> delete p;

> I know that for this to work correctly, Base has to have a virtual
> desrtuctor.

Not necessarily.  If neither Base nor Derived have any resources to free,
then having any destructor is unnecessary.  But, in most cases, you are
correct and Base must have a virtual destructor.

Quote:
> But does Derived have to have a virtual destructor? (Assume
> that no class inherits from Derived).

Derived WILL have a virtual destructor because it is a derived class of a
class having a virtual destructor.  If a compiled class can find the
destructor of a Base object via the vtable, it must also be able to find the
destructor of any derived class in the same way.

Do you have to declare this?  No.  But it eliminates confusion and lookup
time on your maintainers' part to declare it as such anyway.

faa

--



Tue, 29 Jan 2002 03:00:00 GMT  
 Virtual destructor question

Quote:



> > Suppose I have some code like the following:
> > class Base {};
> > class Derived : public Base {};

> > Base *p = new Derived;
> > delete p;

> > I know that for this to work correctly, Base has to have a virtual
> > desrtuctor.

> Not necessarily.  If neither Base nor Derived have any resources to free,
> then having any destructor is unnecessary.  But, in most cases, you are
> correct and Base must have a virtual destructor.

The language definition requires a virtual destructor when you delete an
object of a derived type through a pointer to a base type.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com
--



Wed, 30 Jan 2002 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. virtual/non-virtual destructors

2. Virtual pure destructors

3. ATL virtual destructor and events causes crash

4. Use of Virtual function under Destructor

5. Virtual destructor call doesn't work!

6. virtual pure destructor

7. Virtual Destructors Defined In Children

8. Destructors being Virtual

9. virtual pure destructor

10. Problems exporting classes in dll with virtual destructors

11. virtual destructors

12. Problem with virtual destructor order

 

 
Powered by phpBB® Forum Software