Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!tcs!nujoizey!gwu From: gwu@nujoizey.tcs.com (George Wu) Newsgroups: comp.lang.c++ Subject: Re: asking an object for its type Message-ID: <1769@tcs.tcs.com> Date: 19 Feb 91 02:40:31 GMT References: <23984@netcom.COM> Sender: root@tcs.com Reply-To: gwu@nujoizey.tcs.com (George Wu) Organization: Teknekron Communications Systems Lines: 51 In article <23984@netcom.COM>, aed@netcom.COM (Andrew Davidson) writes: |> Here is my problem, I have some processing that only applies for |> certain types of objects. If an object is not of the correct type I |> want to do some error stuff. I have wanted to do this very thing several times, and everytime, I decided my approach was entirely wrong. Anytime you find yourself needing to ask an object it's type, be sure the carefully consider why you need to do so. What you're looking for is not a workaround, but the right way to do things. In most (all?) cases, if some work needs to be done dependant upon the type of an object, that code should be implemented in the classes of those objects. For instance, suppose I wanted to to write something like: switch (object->getType()) { case X: executeForX(); break; case Y: executeForY(); break; // . . . } Instead, I would write this do resemble: class X { void execute(); // . . . }; class Y { void execute(); // . . . }; // . . . object->excute(); where classes X and Y probably inherit a common definition of the execute() method as a virtual function. George ---- George J Wu, Software Engineer | gwu@tcs.com or uunet!tcs!gwu Teknekron Communications Systems, Inc.| (415) 649-3752 2121 Allston Way, Berkeley, CA, 94704 | Quit reading news. Get back to work.