Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.object Subject: Re: inheritance and `type loss' Message-ID: <55775@microsoft.UUCP> Date: 11 Jul 90 18:16:17 GMT References: Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Distribution: comp Organization: Microsoft Corp., Redmond WA Lines: 57 In article sra@ecs.soton.ac.uk (Stephen Adams) writes: >(a) what should (V+V).image yield? "10" or "X"? > (V+1).image "6" or "VI"? > (1+V).image "6" or "VI" or error (in +)? > >(b) what do various object oriented systems actually do? > C++ provides are variety of ways to allow a programmer to either return an int or a roman in the above example. Generalizing the problem to full polymorphic behavior is quite doable -- but ugly, requiring a double dispatch. Say in general, one wants: aDog = aDog + aDog; but in specific one wants: aPoodle = aPoodleF + aPoodleM; aCockerSpaniel = aCockerSpanielF + aCockerSpanielM; aCockapoo = aPoodleF + aCockerSpanielM; aCockapoo = aCockerSpanielF + aPoodleM; --So one can end up specifying a lot of flavors of "+" to get exactly the behavior one wants. [I'm using inter-breeding as a metaphor -- I'm not suggesting the above is a good overloading of "+"] --- void image(int i) { printf("%d\n", i); } class roman1 { protected: int i; public: roman1(int ii) : i(ii) {} operator int() { return i; } // a simplified version of roman numerals -- works for small positive ints :-) friend void image(roman1 r) { while (r.i--) printf("I"); printf("\n"); } }; class roman2 : public roman1 { public: roman2(int i) : roman1(i) {} friend roman2 operator+(int i, roman2 r2) { return i + r2.i; } }; main() { int anInt = 1; roman1 aRoman1 = 2; image(anInt + aRoman1); // prints "3" roman2 aRoman2 = 2; image(anInt + aRoman2); // prints "III" return 0; }