Path: utzoo!censor!dybbuk!yunexus!ists!helios.physics.utoronto.ca!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!usc!zaphod.mps.ohio-state.edu!uwm.edu!bionet!ames!vsi1!daver!tscs!tct!chip From: chip@tct.uucp (Chip Salzenberg) Newsgroups: comp.lang.c++ Subject: Re: asking an object for its type Message-ID: <27C95350.1558@tct.uucp> Date: 25 Feb 91 18:11:28 GMT Article-I.D.: tct.27C95350.1558 References: <1991Feb22.195826.14008@gpu.utcs.utoronto.ca> <27C6DBF3.28A3@tct.uucp> <27114@dime.cs.umass.edu> Organization: Teltronics/TCT, Sarasota, FL Lines: 42 According to connolly@livy.cs.umass.edu (Christopher Connolly): >In article <27C6DBF3.28A3@tct.uucp> chip@tct.uucp (Chip Salzenberg) writes: >>If the "same" operation is actually several operations that are >>distinct in semantic terms (as opposed to implemention), then folding >>them together into one virtual function is a design error. > ^^^^^^^^^^^^ > >Consider the operation "+": I can use simple integer addition if both >my coefficients are integers. The "+" operation results in an integer >in this case. On the other hand, adding an integer to an algebraic >number usually results in another algebraic number. Integer addition >and algebraic number addition are quite different algorithms, >producing quite different results. But both of those algorithms implement "addition" in the sense that a mathemetician may use the word. So I probably would not consider your example to be an implementation of "several different operations [that are] distinct in semantic terms." >I see no way around defining a generic "+" operation which takes >different data types, and returns different data types as a result >(all derived from the "coefficient" class, of course). Sure. Make coefficient an abstract base class. Derive int_coeff (integer) and alg_coeff (algebraic). Have all "+" operations return a coefficient, thus allowing you to use the virtual function mechanism. Make a virtual member function "operator +=", and implement a non-member "operator +" using "+=". Then, the key: a virtual member function "int integer_value(int &n)", which sets "n" to the integer value of the given coefficient and returns true for success, or false for failure. Only int_coeff will define this function to return true; all others will return false. Then use it: coefficient c = coefficient(4) + coefficient(7); int n; if (c.integer_value(n)) cout << "c is " << n << "\n"; else cout << "c isn't an integer!\n";