Overriding the + Operator

10 posts

Flag Post

I want to make a Vector2 Class which would allow me to use mathematical operators instead of having to call .add() .subtract() and so on. It’s not a life or death matter, but it’d be nice to get it to work.

So far I have discovered the Proxy Class and attempted to accomplish the task by overriding the call property method. This has lead me to the following:

a + b

If both a and b are strings, concat.
If one of a or b is a string, toString() the other, concat.
If both a and b are Number/int/uint, add mathematically.
Otherwise, valueOf() each that is not a number or string, toString() each that is still not a number or string and follow the previous rules.

This poses a problem that if anything other than a number (or int/uint) is present, the operation defaults to string concatenation. And I can’t really express a Vector2 as a single number, so no matter what I do, I end up with string concatenation. While I can change the valueOf() and toString() methods, I have no way (that I know of) to control the the + operator at all.

So, is there any way to solve this problem without going completely dodgy?

 
Flag Post

There is no overloading in As3.

 
Flag Post

You can do overloading with Haxe’s abstracts, but that means you won’t be using AS3 anymore.

 
Flag Post

Well, bummer. I can get close, but the fact that addition/concatenation (+) and assignment (=) are both behind-the-scenes and untouchable from the Proxy Class means I can’t quite do it.

 
Flag Post

if your a and b are multiple values a piece, would something like an array not work, or something that can handle multiple int values?

 
Flag Post

I could pretty much use anything, but the functionality I want is that each set of 2 numbers is stored in 1 variable and that I am able to go var1 + var2 to return a variable of the same type for which each number is the sum of the corresponding numbers in the previous two variables. I am completely at a loss for how to do this, seemingly because it’s not possible.

ie.

var var1 = (6,2);
var var2 = (3,4);
var var3 = var1 + var2;
trace(var3); // (9,6);
 
Flag Post

Point.add is the closest you will get. As said earlier, AS3 does not support overloading.

 
Flag Post

Oh well. Maybe in a future version of Flash Player or something…

 
Flag Post

Yeah hopefully. I have the same thing with vector and matrix classes, the C# version is really nice to use and the AS one a bit ugly, but we just have to put up with it.

 
Flag Post

How we can use the operater overriding and where we use during the coding time.