home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / cplus / 16784 < prev    next >
Encoding:
Text File  |  1992-11-23  |  2.0 KB  |  41 lines

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