home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / cplus / 12919 < prev    next >
Encoding:
Text File  |  1992-08-26  |  2.0 KB  |  61 lines

  1. Path: sparky!uunet!cs.utexas.edu!sdd.hp.com!think.com!barmar
  2. From: barmar@think.com (Barry Margolin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: backwards casting for lackof better term
  5. Date: 26 Aug 1992 17:54:50 GMT
  6. Organization: Thinking Machines Corporation, Cambridge MA, USA
  7. Lines: 49
  8. Message-ID: <17gghaINN3pe@early-bird.think.com>
  9. References: <6370@lhdsy1.lahabra.chevron.com>
  10. NNTP-Posting-Host: telecaster.think.com
  11.  
  12. In article <6370@lhdsy1.lahabra.chevron.com> hwrvo@kato.lahabra.chevron.com (W.R. Volz) writes:
  13. >The question: what does CreateAAorAborAC return, or, what does the function
  14. >protptype looklike? A * CreateAAorABorAC(int) or what.
  15.  
  16. Yes, that's it.
  17.  
  18. >Can this function be written so that it is 
  19. >independant of any new classes that might be created from A, or, what 
  20. >happens if I create a new class AD.  If all the derived classes handle 
  21. >their initializations, can this routine be written so that it is 
  22. >independant of new classes that might be created later, like AD?
  23.  
  24. Unfortunately, no.  While the overall structure will stay the same, if you
  25. add new derived classes you have to update CreateAAorABorAC to add entries
  26. for them to to the switch statement.  Hopefully your actual application
  27. uses a better name for the function than CreateAAorABorAC, so that you
  28. won't need to change the function name as well!
  29.  
  30. Another way to implement it is with a dispatch table:
  31.  
  32. A*(*creator_table)[] = {
  33.     AA::CreateA,
  34.     AB::CreateA,
  35.     AC::CreateA
  36. };
  37.  
  38. const int creator_table_size = sizeof(creator_table) / sizeof(*creator_table);
  39.  
  40. A* CreateAAorABorAC (int type_index) {
  41.     if (i < creator_table_size)
  42.        return (creator_table[i].fn)();
  43.     error(...);
  44. }
  45.  
  46. class AA: public A {
  47.     // ...
  48.   public:
  49.     static A* CreateA() {return (A*) new AA;}
  50. }
  51.  
  52. // same for AB and AC
  53.  
  54. Now if you create an AD class, you just make sure that it has a CreateA
  55. static member function and add it to the creator_table.
  56. -- 
  57. Barry Margolin
  58. System Manager, Thinking Machines Corp.
  59.  
  60. barmar@think.com          {uunet,harvard}!think!barmar
  61.