In c++, why we must overloading +=, -=, +, - operator beside just overloading + and - operator? Here is an example:
In C++, when I create a Point class, I will do:
class Point { public: int x, y; public: Point(int X, int Y) : x(X), y(Y) {} //Assignment operator void operator=(Point a) { x = a.x; y = a.y; } //The += and -= operator, this seem problematic for me. void operator+=(Point a) { x += a.x; y += a.y; } void operator-=(Point a) { x -= a.x; y -= a.y; } //The + and - operator Point operator+(Point a) { return Point(x + a.x, y + a.y); } Point operator-(Point a) { return Point(x - a.x, y - a.y); } }; But in some other language like C# for example, we don't need to overloading the += and -= operator:
public class Point { public int x, y; public Point(int X, int Y) { x = X; y = Y; } //We don't need to overloading =, += and -= operator in C#, all I need to do is overload + and - operator public static Point operator+(Point a, Point b) { return Point(a.x + b.x, a.y + b.y); } public static Point operator-(Point a, Point b) { return Point(a.x - b.x, a.y - b.y); } } And both will work same as c++!
So I already know that if we overloading like c++, we can easier control which operator this class can have. But what else it can do?
I'm also new in c++ and I just learn overloading operator today.
+=and-=can fundamentally be more efficient than+and-(the latter need to create a new object, after all). So if anything it makes sense to implement+and-in terms of+=and-=, not the other way round.+=and-=is faster?