Re: abstract class question about operators

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance




"t f" <thetoefungus@xxxxxxxxx> wrote in message
news:e6CfBZBuHHA.1164@xxxxxxxxxxxxxxxxxxxxxxx
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?

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



.



Relevant Pages