Re: virtual destructor
From: Luther Baker (lutherbaker_at_yahoo.com)
Date: 05/24/04
- Next message: ninth: "xlC,xlC_r"
- Previous message: Sumit Rajan: "Re: string to integer"
- In reply to: JKop: "Re: virtual destructor"
- Next in thread: jeffc: "Re: virtual destructor"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 24 May 2004 02:12:23 -0500
JKop wrote:
>
> And why would you do the following:
>
>
> Mammal restt = new Dog;
>
> delete restt;
>
I'm not sure I understand your question - so I apologize if I'm off
base, but ... programming to interfaces is a fundamental principal of OO
design. One way to do this is to use base class pointers to concrete
derived class implementations.
To get a base class pointer to call a derived class method, the method
must be declared virtual. Lets look at a base class Theme:
Theme* theme = ThemeFactory.getUserTheme();
In this case, the factory will return a concrete instance of a class
derived from theme. Any call to a virtual method made by *theme* will
call the derived class' method. Any call to a non-virtual method made by
*theme* will enact its own implementation of said method.
Now, if the Derived Class constructor creates resources. For example,
the AMEX theme creates a pool of database connections to the Dow Jones
interface portal available on the local network. So, unbeknownst to the
base class, the derived class has allocated resources.
The resources could be heap memory for char*s or it might be something
more elaborate. Whatever the case - when the base class pointer is
eventually deleted, how are the resources the derived class acquired
going to be released?
If the base class destructor is NOT virtual, then the derived class will
never be told that the base class pointer has been deleted. If the
destructor IS virtual, then the derived class destructor will be called.
Some smaller projects may in fact get by without using virtual
destructors, but in most large projects - it would be the norm that
classes should indeed have virtual destructors.
For a better example and discussion on the topic, see Exceptional C++,
Herb Sutter, pg 75, and work through item 21. Specifically, take a look
at the guideline on page 77.
-Luther
- Next message: ninth: "xlC,xlC_r"
- Previous message: Sumit Rajan: "Re: string to integer"
- In reply to: JKop: "Re: virtual destructor"
- Next in thread: jeffc: "Re: virtual destructor"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|