home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!secapl!Cookie!frank
- From: frank@Cookie.secapl.com (Frank Adams)
- Subject: Re: virtual functions need virtual destructors ?
- Message-ID: <1992Nov23.172304.110821@Cookie.secapl.com>
- Date: Mon, 23 Nov 1992 17:23:04 GMT
- References: <kilitzir.722528914@news.forth.gr>
- Organization: Security APL, Inc.
- Lines: 30
-
- In article <kilitzir.722528914@news.forth.gr> kilitzir@antigone.csi.forth.gr (Xristos Kilitzirakis) writes:
- >
- >Why do virtual functions need virtual destructors ?
-
- Two reasons.
-
- 1) There is a default assumption that when you have virtual functions, you
- will be making virtual calls: that is, calls where you don't know the actual
- type of the object whose member function is being called, because you have
- only a pointer or reference to the object, and might actually be dealing
- with a subclass. Note that there is little point in having a pointer to
- class with no virtual functions that might actually point to a subclass --
- there is no [type-safe] way of using the actual class. Since you are likely
- to have such a reference, it is likely that you will want to delete by means
- of it -- and this will only work if you have a virtual destructor.
- (Furthermore, the bugs that result from failing to make the destructor
- virtual are pretty subtle.)
-
- 2) The cost of having a virtual destructor in a class with virtual functions
- is very small. The run-time cost of calling a virtual function is not
- large, and the space cost is simply one additional slot in the virtual
- function table for each class. By contrast, adding a virtual destructor to
- a class which otherwise had no virtual functions requires adding a virtual
- function table pointer to each *instance* of the class -- which can be quite
- costly if the class doesn't use much data and there are lots of them.
-
- So a class with virtual functions can cheaply be given a virtual destructor,
- which costs little and can easily prevent difficult bugs. Giving a class
- with no virtual functions a virtual destructor is more expensive, and
- unlikely to do much good.
-