Is it possible to simplify overridden operators?

Hello everyone,

New poster here and semi-experienced with c++.
I have a quick question; Is it possible to simplify overridden operators for custom classes?
This is the case:
For school we have to make a game with Vector Motion, currently in 2D. ANd in most programs I've worked with (XNA C#, Unity) you can use '+', '-' etc. operands.
I managed to get them working in C++ like so:

IN MY VECTOR2.H:
void operator += (Vector2* vector) {x+=vector->x; y+=vector->y;}

IN MY GAME.CPP:
player.transform.velocity = new Vector2(player.xVelocity, player.yVelocity);
player.transform.velocity->operator+=(player.transform.velocity);

But I just want to be able to do something like Vector2+=Vector2 instead of Vector2(function_call)(function_parameter).

Is this possible?
I have also looked at http://www.cplusplus.com/doc/tutorial/classes2/, but when I use this method I'm getting an error about arithmetics.

Regards,

Zubaja
looks like you're trying to overload some operators, but i didn't completely understand what you want to do.
could you post the code, that is causing the errors
Well then just do...
 `` `` ``*player.transform.velocity += player.transform.velocity;``

Doesnt it work? Whats the error in that case?
Also you should declare your operators differently:

 `` `` ``Vector2& operator += (const Vector2& vector) { x += vector.x; y += vector.y; return *this; }``

This is the best way to do it.
The return type (Vector2& at the beginning) allows you to do chains of +='s.
the 'const Vector2& vector' is the best way to pass a constant parameter, something you don't want to modify.
The return *this is required for the chain to work.

Also, the parameter is not a pointer. Pointers are harder to work with and make things just harder in such a context.

Also it's better for you if you don't allocate the vector with the new operator, you don't really need that.
Last edited on
`*player.transform.velocity += player.transform.velocity;`
Works like a charm.

I've also tried the second approach, but I get this error:
`Expression must have integral or enum type`

I'll keep on using the pointer for now.
Thanks a bunch!
Topic archived. No new replies allowed.