Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!milano!cadillac!vaughan@mcc.com From: vaughan@mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: Re: Why ask an object its type?? (was: libraries, compilers, class...) Message-ID: <11810@cadillac.CAD.MCC.COM> Date: 5 Oct 90 19:04:23 GMT References: <995@halley.UUCP> <57751@microsoft.UUCP> Sender: news@cadillac.CAD.MCC.COM Reply-To: vaughan@mcc.com (Paul Vaughan) Organization: MCC VLSI CAD Program Lines: 46 In-reply-to: cline@cheetah.ece.clarkson.edu (Marshall Cline) From: cline@cheetah.ece.clarkson.edu (Marshall Cline) . . . I'd like to ask a key question: ``WHY ASK AN OBJECT ITS TYPE?'' There are several answers that I can think of, and presumably others will add some more. [1] you might ask an object its type to determine if a particular message is applicable. This is one of the worst possible (mis)uses of the CRO concept, since it is the antithesis of strong typing. [2] you might ask an object its type so you can do a safe down-cast. This often amounts to the same thing as [1], since if both the static type of the reference and the dynamic type of the object have the desired member function, then the (strongly typed) virtual mechanism is preferred. [3] if you're reading an object from persistent store (or from a network wire, etc), you absolutely need to ask it its type since there is no way for a compiler to statically determine its type. We occassionally do 2. You note that this is similar to reason 1, but knowing the type is a little more fundamental than knowing if a particular message is applicable. However, the main reason we do this is to accomplish modularity. One part of the program can really only deal with types it understands but the communication between the parts of the program uses a particular base type. There are reasons not to put all the methods onto the base type. We also use run-time type information for other purposes. For instance, we dynamically generate, compile and link code from user input. Knowing the type is important for writing out the code and giving the user the most power. Also, we essentially allow users (of our application) to interactively make pointer assignments. For this we do a run-time check just like the compiler would have done if it were a code statement. About the only alternative is to put all possible methods on the base class with null definitions. However, this eventually becomes equivalent to programming with ordinary C structs and functions. Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan