Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!mips!sgi!shinobu!odin!sgihub!dragon!xanadu.wpd.sgi.com!pal From: pal@xanadu.wpd.sgi.com (Anil Pal) Newsgroups: comp.lang.c++ Subject: Re: Lacking parameterized types and multi-methods.... Keywords: fyi Message-ID: <1991Mar8.014740.7924@dragon.wpd.sgi.com> Date: 8 Mar 91 01:47:40 GMT References: <11764@pasteur.Berkeley.EDU> Sender: news@dragon.wpd.sgi.com (CNews Account) Reply-To: pal@wpd.sgi.com Organization: Silicon Graphics, Inc. Lines: 45 In article <11764@pasteur.Berkeley.EDU>, maverick@fir.Berkeley.EDU (Vance Maverick) writes: |> |> class Base { |> public: |> virtual int operator < (const Base &) = 0; |> virtual int operator >= (const Base &) = 0; |> }; |> |> class IntVal : public Base { |> public: |> int val; |> |> int operator < (const IntVal &i) |> { return (val < i.val); } |> int operator >= (const IntVal &i) |> { return (val >= i.val); } |> |> /* Comparing an IntVal to a Base? Flip the arguments to |> see if the Base isn't really an IntVal after all */ |> |> int operator < (const Base &b) |> { return (b >= *this); } |> }; Not so fast. Consider Base& x = IntVal(2); Base& y = IntVal(3); if (x < y) ... This will invoke x.operator<(y), which is virtual to IntVal::operator<(Base&) Since there is no Base.operator<(IntVal&), this will call operator<(Base&), which will (through the magic of virtual functions) bring you back to IntVal::operator<(Base&), where, mirabile dictu, you will switch back and call... you guessed it. Infinite loop. To break the cycle, you have to make use of the knowledge that one operand is an IntVal, which means that there has to be a Base::operator<(IntVal&) (and, liekwise, a Base::operator<(FloatVal)). Also, if you want the arguments to be const, you need to declare the operators consts as well, or else you won't be able to do the flip. And finally, you will need to define FloatVal::operator<(IntVal&) and vice versa, as well; they should raise an error condition, given your requirements. -- Anil A. Pal, Silicon Graphics, Inc. pal@wpd.sgi.com (415)-335-7279