From: Dragan Milenkovic on
On 07/13/2010 12:27 AM, cpp4ever wrote:
> On 07/12/2010 02:15 PM, Goran wrote:
[snip]
>> P.S. BTW, in raw C, these things work with primitive types (e.g. int,
>> float) through implicit conversions, not through operator
>> overloading ;-) Perhaps you should try that instead, but then again,
>> I'd be wary.
>>
>>
>
> Without careful design, I'd agree, but in this case I would define the
> operator += () in a standard form as follows:
>
>
> class A
> {
> public:
> virtual const A&operator += (const A&);
> }
>
> class B : public A
> {
> public:
> virtual const B&operator += (const A&);
> const B&operator += (const B&)
> }
>
> B operator + (const A&inp1, const B&inp2)
> {
> B tmp = inp2;
> tmp += inp1;
> return tmp;
> }
>
> So for any class operator +=() will always returns a const reference to
> the class object that handled it. Whereas for operator +() the simplest
> solution is to return by value the most appropriate class type.

Allow me to build up on your design...

class C : public A
{
public:
virtual const C & operator += (const A&);
const C& operator += (const C&)
};

Now, given:
C c;
B b;

.... what would this do and how should it be implemented?
b += c;

Will it call B::operator+=(const A&) ? What will it do?
Does B know about C, too? And when we add a new type D,
will the knowledge of D need to be add everywhere? This
is an obvious abuse of inheritance and virtual functions.
The original advice regarding conversion vs inheritance
was sound.

--
Dragan


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]