Writing classes that use operators ( + - / * etc)

A rather general question :slight_smile:

Is it possible to create classes that use the comparator and combination operators?

For example, I would like to be able to write something like


     Vector2D a = new Vector2D(100, 200);
     Vector2D b = new Vector2D(100, 200);

     Vector2D x = a + b;

     ( x == Vector2D(200, 400) )

    OR

    boolean x = (a > b);

    ( x == false )

Writing it that way is far more intuitive (for me anyway), than say having a method Vector2D.Add(Vector2D a, Vector2D b);

I seem to remember that this is possible in either C++ or C#, but cant recall where I saw the example.

It is not . This is called operator overloading . It does exist for the String class (“a”+“b” = “ab”) but that’s about it.
You cannot define your own operators overloading like C++ .

yep.

Yeah, you’ll basically need to put functions with relevant names myObject.add(myObject2) myObject.scale(myObject2) etc.

I personally like this because if you’ve seen a game engine in another language (take the Unreal Engine) you’ll go insane over how many ridiculous operators they have, like using ^ to represent the dot product (not remembering exactly, but you get the idea).

well bummer :-\

ohh yeh.

Yeh, that’s what I’ve been doing. Unfortunately at times it leads to massive spaghetti-code method calls which i write at 3 in the morning and then have to spend an hour unpicking in the cold light of day :slight_smile:

Thanks anyway guys

If you get spaghetti code with a.plus(b).minus©.scale(30)… Its still spaghetti code with operator overloading. With the added obfuscation on what the operator is really doing (I won’t get into some doggy things folks do with types and templates). C++ also forces “copy” semantics IIRC where you can define your own with explicit methods and document them. You can even provide different semantics in the same object, like addTo() and add() for example.

One piece of code i was working on had a simple c=a+b+c; statement. Only thing was it didn’t really add a b or c and the result assigned to c was so full of side effects we rewrote everything with explicit add methods.

I would not use operator overloading very often if at all, even when its available (One exception would be a complex number class for example, but again forced copy semantics may remove the benefit).

Oh no! Let’s not go there again!

Use scala.