Click to See Complete Forum and Search --> : Operator overloading


rliq
December 17th, 2008, 08:10 PM
Say I wanted to override the '+' operator for the following class:


public class MyClass
{
private MyType _mySecretInternalRepresentation; // MyType maybe UInt32 for example

public static MyClass operator+(MyClass a, MyClass b)
{
// code required here
}
}

Ok, *I*know how to add a to b, but how can i get at their internal representation so I can perform the add, without exposing the internal representation (making it public) to everyone and breaking one of the fundamental laws of OO ?

Am I missing something? I'm sure in C++ I had access to private members of the *same* class within an operator overload function.

Microsoft give an example in the documentation (see operator overloading C# vs Java) for complex numbers, but their ComplexNumber class has public members which is not good because individual parts of the complex number can be modified independently by external code.

rliq
December 17th, 2008, 08:51 PM
Sorted....

If the operator+ function is NOT static, then you do get access to the parameters private members:

public class MyClass
{
private MyType _mySecretInternalRepresentation; // MyType maybe UInt32 for example

public MyClass operator+(MyClass other)
{
other._mySecretInternalRepresentation; // can access here
}
}

Mutant_Fruit
December 18th, 2008, 04:09 AM
Sorted....

If the operator+ function is NOT static, then you do get access to the parameters private members:

public class MyClass
{
private MyType _mySecretInternalRepresentation; // MyType maybe UInt32 for example

public MyClass operator+(MyClass other)
{
other._mySecretInternalRepresentation; // can access here
}
}
Did you try compiling that? It doesn't compile, the operator overload must be static.



Ok, *I*know how to add a to b, but how can i get at their internal representation so I can perform the add, without exposing the internal representation (making it public) to everyone and breaking one of the fundamental laws of OO ?

You should have just tried rather than asking ;) It works exactly the way you'd expect it to:


public class MyClass
{
private int value; // MyType maybe UInt32 for example

public static MyClass operator +(MyClass left, MyClass right)
{
return new MyClass { value = left.value + right.value };
}
}

darwen
December 18th, 2008, 05:10 AM
As you've found out the operator+ method is a member of the class (even though it's static) so it has access to the private data of instances of the same class.

C# doesn't support instance-level operating overloading (it's not C++). The correct way of overloading an operator is to use a static method as you have done.

Darwen.