Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!tdatirv!sarima From: sarima@tdatirv.UUCP (Stanley Friesen) Newsgroups: comp.lang.c++ Subject: Re: virtual operators Message-ID: <16@tdatirv.UUCP> Date: 3 Jun 91 19:48:48 GMT References: <1991Jun1.175904.20181@ux1.cso.uiuc.edu> Reply-To: sarima@tdatirv.UUCP (Stanley Friesen) Organization: Teradata Corp., Irvine Lines: 57 I think this is getting to FAQ level. In article <1991Jun1.175904.20181@ux1.cso.uiuc.edu> bernied@yoyodyne.ncsa.uiuc.edu (Bernhard Damberger) writes: > > I 'am having some problems with virtual operators... >class Base { > ... >public: > virtual int operator< (Base &) const; // less than operator for Base > virtual int operator> (Base &) const; // greater than operator > ... // etc... >}; > >class TestInt : public virtual Base { > ... >public: > virtual int operator< (const TestInt &) const; // overide Base > virtual int operator> (const TestInt &) const; // overide Base > ... // overide the rest of Base's relational operators >}; OK, here's your problem. These do *not*, I repeat, *not*, override the "corresponding" virtual functions in Base! And why not? Because they do not have *exactly* *matching* signatures. By making the parameters 'const TestInt &' instead of 'Base &' you are *replacing*, not overriding, the functions in Base. Now, since the functions in Base have never been overridden, then a call through a Base pointer or reference will, naturally, use the pre-defined base functions. <> > The problem occurs when the "less than" operator is applied. I >want CFront to call the most specific operator< as possible. In this >case that would mean if I called BinaryTree::insert(foo), where foo is >a TestInt pointer, I would want CFront to call TestInt::operator<(TestInt &) >But, instead it calls the more basic Base::operator< (instead of >TestInt::operator<). As indeed it should, given the above definitions. > So how do I get CFront to use the virtual operators? When are >the types bound (it looks like at compile time instead of run time)? >How do I get CFront to call the most specific operator method? This is quite simple, make the TestInt relational functions take parameters of type (Base &). Oh, you need 'const' parameters? Then you need to add the const qualified forms as virtual functions in the definition of class Base. -- --------------- uunet!tdatirv!sarima (Stanley Friesen)