Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why we must overloading += and -= beside just overloading + and – operator?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

The typical operator+= is more efficient than a = a + b, and cannot be implemented in terms of operator+. It can be the other way around though:

struct foo {
    int value = 42;
    foo& operator+=(const foo& other) {
         this.value += other.value;
         return *this;
    }
    foo operator+(const foo& other) const {
         foo result = *this;
         result += other;   // reuse operator+=
         return result;
    }
};

Note how operator+ must create a new instance, while operator+= merely adds member of already existing instances.

In general operator+= can do something else entirely and might not be related to operator+ at all.

The same holds for operator-= vs operator-.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading