Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!zaphod.mps.ohio-state.edu!think.com!barmar From: barmar@think.com (Barry Margolin) Newsgroups: comp.lang.c++ Subject: Re: asking an object for its type Message-ID: <1991Feb19.023528.29494@Think.COM> Date: 19 Feb 91 02:35:28 GMT References: <23984@netcom.COM> <1190@sheol.UUCP> <1991Feb19.000449.22255@gpu.utcs.utoronto.ca> Sender: news@Think.COM Organization: Thinking Machines Corporation, Cambridge MA, USA Lines: 35 In article <1991Feb19.000449.22255@gpu.utcs.utoronto.ca> craig@gpu.utcs.utoronto.ca (Craig Hubley) writes: >Arg. A totally contextual algorithm. I do NOT want to write a special >function for all shapes to respond to this. What I would really like to >do is something like: > "if x.type=circle then if x.diameter > 30 then return x" Even in languages that provide a way to do that, you probably wouldn't want to write it that way, because it doesn't handle derived classes properly. For instance, if square is derived from regular_polygon and quadrilateral, x.type can't be all three. What you want is something like if x.is_circle() ... or if x.is_of_type("circle") ... The latter can be implemented by writing something like int circle::is_of_type(char *type) { return (strcmp(type, "circle") == 0) || shape::is_of_type(type); } int square::is_of_type(char *type) { return (strcmp(type, "square") == 0) || quadrilateral::is_of_type(type) || regular_polygon::is_of_type(type); } -- Barry Margolin, Thinking Machines Corp. barmar@think.com {uunet,harvard}!think!barmar