hi
just a quick question - i have the something like the following
public abstract class ClassA
{
protected int iA;
public int Value { get {return iA;} set { iA = value;}}
public ClassA(int value)
{ iA = value; }
public static ClassA operator +(ClassA a1, ClassA a2)
{
a1.Value = a1.Value + a2.Value;
return a1;
}
public static ClassA operator -(ClassA a1, ClassA a2)
{
a1.Value = a1.Value - a2.Value;
return a1;
}
}
public class ClassB : ClassA
{
public ClassB(int value) : base(value)
{ }
}
public class ClassC : ClassA
{
public ClassB(int value) : base(value)
{ }
}
Problem is, if i try this
ClassB cb1 = new ClassB(1);
ClassB cb2 = new ClassB(2);
ClassB cb3 = cb1 + cb2;
I get an error as cb1 + cb2 is of type ClassA....
Question: Is there a way of putting all my operator overloads in the base
class and instead of having to put them in each of the derived classes?
Thanks
t f
Jon Skeet [C# MVP] - 26 Jun 2007 18:54 GMT
<snip>
> Question: Is there a way of putting all my operator overloads in the base
> class and instead of having to put them in each of the derived classes?
No - the base class would have to know what to do with each of the
derived classes, which it shouldn't care about. (You also can't write
an operator which doesn't use your own type as one of the operands,
IIRC.)
You'll need to overload the operators in each derived class you want to
use them for.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Michael S - 27 Jun 2007 11:39 GMT
> No - the base class would have to know what to do with each of the
> derived classes, which it shouldn't care about. (You also can't write
> an operator which doesn't use your own type as one of the operands,
> IIRC.)
What Jon is saying here is that:
public static ClassA operator +(ClassA a1, ClassA a2)
{
a1.Value = a1.Value + a2.Value;
return a1;
}
should be:
public static ClassA operator +(ClassA a1, ClassA a2)
{
return new ClassA(a1.Value + a2.Value);
}
- Michael S
Jon Skeet [C# MVP] - 27 Jun 2007 12:09 GMT
<snip>
> What Jon is saying here is that:
In fact, that's not quite what I was saying - I hadn't spotted that
the original code was changing an existing value rather than creating
a new one. I'd certainly have said that *as well* if I'd spotted it
though :)
Jon
Ben Voigt [C++ MVP] - 26 Jun 2007 19:02 GMT
> hi
>
[quoted text clipped - 43 lines]
> Question: Is there a way of putting all my operator overloads in the base
> class and instead of having to put them in each of the derived classes?
You've already done so. You've also discovered the limitations, which have
to do with covariance.
This method could certainly work for
static bool operator!=(ClassA a1, ClassA a2);
and similar, but the return type must be fixed and doesn't vary with the
derived type.
> Thanks
> t f