Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!wuarchive!brutus.cs.uiuc.edu!ux1.cso.uiuc.edu!ux1.cso.uiuc.edu!m.cs.uiuc.edu!p.cs.uiuc.edu!johnson From: johnson@p.cs.uiuc.edu Newsgroups: comp.lang.c++ Subject: Re: Getting Type Information at Runtime Message-ID: <77300052@p.cs.uiuc.edu> Date: 26 May 90 12:50:00 GMT References: <40876@brunix.UUCP> Lines: 32 Nf-ID: #R:brunix.UUCP:40876:p.cs.uiuc.edu:77300052:000:1378 Nf-From: p.cs.uiuc.edu!johnson May 26 07:50:00 1990 Scott Meyers writes: >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; > } I assume that you have a better reason for wanting the type of an object at runtime, since the purpose of virtual functions is to eliminate code like this. You are requiring that the type of an object be represented by an integer, that this integer can be assigned without any centralized coordination, and that it is possible to compare integers representing types to test whether one is a subtype of the other. One way to solve this problem is to create an object for each type. Define a type ClassObject with member variables "name" and "supertypes". Every class that you define can have a static member variable of type ClassObject that is initialized to know the name and supertypes of the class that it represents, as well as a "type()" function that returns its address. We do something like this for Choices to implement our debugger and browser. We do NOT use it in switch statements. This has the disadvantage that every class has to be a subclass of "TypeableObject". Ralph Johnson -- University of Illinois at Urbana-Champaign