home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!ascent!eb
- From: eb@ascent.com (Ed Barton)
- Subject: Re: member test?
- In-reply-to: haechler@bernina.ethz.ch's message of 6 Nov 92 08:16:58 GMT
- Message-ID: <EB.92Nov9085335@ascent.ascent.com>
- Date: 9 Nov 92 08:53:35
- References: <1992Nov6.081658.29693@bernina.ethz.ch>
- Organization: Ascent Technology, Inc., Cambridge Massachusetts
- Lines: 45
-
- In article <1992Nov6.081658.29693@bernina.ethz.ch> haechler@bernina.ethz.ch (Stefan Haechler) writes:
-
- How can I know which dynamic type has a variable ?
- e.g.
- class A { .... } ;
- class B: public A { ... } ;
- // variable declaration
- A *a ;
- // initialization
- a = new B;
- // now the dynamic type of "a" is B
- // my question:
- // is there a statement for testing if a is member of B
- // e.g
- if (member(a,B) == true) ..... else ..... ;
-
-
- [I tried to reply via E-mail, but it bounced.]
-
- You are asking for something called "runtime type identification" or
- RTTI, which has been much discussed in the C++ community and may
- eventually make it into the language in some limited form. But the
- answer for now is that no, you can't do it, unless you implement it
- yourself by using some type of virtual function that you redefine in
- each subclass.
-
- The software-design answer is that you shouldn't have to know the
- answer to this question, and that there may be something wrong with
- the design if you need to ask it. If you know only that something is
- a pointer-to-A, you should be using only the methods and virtual
- functions that are part of the interface defined by class A.
-
- In the case where you know about subclass B while class A is being
- designed, and where the notion of possible B-ness is part of the
- design of class A, you should have a virtual function
-
- class B;
-
- class A { ... virtual B* asB() { return 0; } ... };
-
- class B : public A { ... B* asB() { return this; } ... };
-
- which is type-safe and doesn't involve any nasty casts.
-
-
-