home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!sdd.hp.com!think.com!barmar
- From: barmar@think.com (Barry Margolin)
- Newsgroups: comp.lang.c++
- Subject: Re: backwards casting for lackof better term
- Date: 26 Aug 1992 17:54:50 GMT
- Organization: Thinking Machines Corporation, Cambridge MA, USA
- Lines: 49
- Message-ID: <17gghaINN3pe@early-bird.think.com>
- References: <6370@lhdsy1.lahabra.chevron.com>
- NNTP-Posting-Host: telecaster.think.com
-
- In article <6370@lhdsy1.lahabra.chevron.com> hwrvo@kato.lahabra.chevron.com (W.R. Volz) writes:
- >The question: what does CreateAAorAborAC return, or, what does the function
- >protptype looklike? A * CreateAAorABorAC(int) or what.
-
- Yes, that's it.
-
- >Can this function be written so that it is
- >independant of any new classes that might be created from A, or, what
- >happens if I create a new class AD. If all the derived classes handle
- >their initializations, can this routine be written so that it is
- >independant of new classes that might be created later, like AD?
-
- Unfortunately, no. While the overall structure will stay the same, if you
- add new derived classes you have to update CreateAAorABorAC to add entries
- for them to to the switch statement. Hopefully your actual application
- uses a better name for the function than CreateAAorABorAC, so that you
- won't need to change the function name as well!
-
- Another way to implement it is with a dispatch table:
-
- A*(*creator_table)[] = {
- AA::CreateA,
- AB::CreateA,
- AC::CreateA
- };
-
- const int creator_table_size = sizeof(creator_table) / sizeof(*creator_table);
-
- A* CreateAAorABorAC (int type_index) {
- if (i < creator_table_size)
- return (creator_table[i].fn)();
- error(...);
- }
-
- class AA: public A {
- // ...
- public:
- static A* CreateA() {return (A*) new AA;}
- }
-
- // same for AB and AC
-
- Now if you create an AD class, you just make sure that it has a CreateA
- static member function and add it to the creator_table.
- --
- Barry Margolin
- System Manager, Thinking Machines Corp.
-
- barmar@think.com {uunet,harvard}!think!barmar
-