home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / cplus / 15968 < prev    next >
Encoding:
Text File  |  1992-11-09  |  1.9 KB  |  57 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!ascent!eb
  3. From: eb@ascent.com (Ed Barton)
  4. Subject: Re: member test?
  5. In-reply-to: haechler@bernina.ethz.ch's message of 6 Nov 92 08:16:58 GMT
  6. Message-ID: <EB.92Nov9085335@ascent.ascent.com>
  7. Date: 9 Nov 92 08:53:35
  8. References: <1992Nov6.081658.29693@bernina.ethz.ch>
  9. Organization: Ascent Technology, Inc., Cambridge Massachusetts
  10. Lines: 45
  11.  
  12. In article <1992Nov6.081658.29693@bernina.ethz.ch> haechler@bernina.ethz.ch (Stefan Haechler) writes:
  13.  
  14.    How can I know which dynamic type has a variable ?
  15.    e.g.
  16.    class A { .... } ;
  17.    class B: public A { ... } ;
  18.    // variable declaration 
  19.    A *a ;
  20.    // initialization
  21.    a = new B;
  22.    // now the dynamic type of "a" is B
  23.    // my question:
  24.    // is there a statement for testing if a is member of B
  25.    // e.g 
  26.      if (member(a,B) == true) ..... else ..... ;
  27.  
  28.  
  29. [I tried to reply via E-mail, but it bounced.]
  30.  
  31. You are asking for something called "runtime type identification" or
  32. RTTI, which has been much discussed in the C++ community and may
  33. eventually make it into the language in some limited form.  But the
  34. answer for now is that no, you can't do it, unless you implement it
  35. yourself by using some type of virtual function that you redefine in
  36. each subclass.
  37.  
  38. The software-design answer is that you shouldn't have to know the
  39. answer to this question, and that there may be something wrong with
  40. the design if you need to ask it.  If you know only that something is
  41. a pointer-to-A, you should be using only the methods and virtual
  42. functions that are part of the interface defined by class A.
  43.  
  44. In the case where you know about subclass B while class A is being
  45. designed, and where the notion of possible B-ness is part of the
  46. design of class A, you should have a virtual function
  47.  
  48. class B;
  49.  
  50. class A { ... virtual B* asB() { return 0; } ... };
  51.  
  52. class B : public A { ... B* asB() { return this; } ... };
  53.  
  54. which is type-safe and doesn't involve any nasty casts.
  55.  
  56.  
  57.