Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!brunix!sdm From: sdm@cs.brown.edu (Scott Meyers) Newsgroups: comp.lang.c++ Subject: Getting Type Information at Runtime Message-ID: <40876@brunix.UUCP> Date: 25 May 90 15:58:40 GMT Sender: news@brunix.UUCP Reply-To: sdm@cs.brown.edu (Scott Meyers) Organization: Brown University Department of Computer Science Lines: 43 I'm currently investigating ways to get the type of an object at runtime. What I want to come up with is a simple way to do things like switch (object->type()) { case class1: dosomething1(); break; case class2: dosomething2(); break; case class3: dosomething3(); break; } This rules out simply returning a string containing the classname. I'd also like the scheme to be fairly foolproof and robust, meaning that multiple people working semi-independently on the same system can easily create classes that support the protocol without stepping on each other's toes, and adding new classes doesn't normally require modifying anything outside that class. This rules out using an enumerated type. A standard scheme seems to be to declare a static char in each class, then use the address of that char as the identifier for the class. This approach seems promising, but in trying to put all the pieces together, I've found it isn't always as smooth as I'd hoped. For example, cfront complains if the static char isn't initialized, so you have to put superfluous initializations in your code... Finally, I'd like the approach to be extendable so that I can test "isa" relationships. That is, I can say things like if (isa(object1, object2)) ... and the condition will evaluate to true iff object1 and object2 are of the same class or there is a public inheritance path from object2 to object1. It should also be possible to test this relationship using class identifiers, e.g., something like if (isa(object1, placeHolderForClassX)) ... if (isa(placeHolderForClassX, object1)) ... I know that various libraries have implemented schemes that offer this kind of functionality. What I'd like to know is how they do it, and what the advantages and disadvantages are. Is there a simple, foolproof, robust, way to get and test class relationships at runtime? Scott Meyers sdm@cs.brown.edu