1

In order to become more familiar with C++, I'm implementing a class to manipulate complex numbers.

class Complex {
    private:
        double _real;
        double _imag;

    public:
        Complex();
        Complex(double real, double imag);
        Complex(const Complex& z);

        Complex operator+(const Complex& u) const;
        Complex operator+=(const Complex& u);
};

I already overloaded the + operator which works as expected:

Complex Complex::operator+(const Complex& u) const {
    Complex z(_real + u._real, _imag + u._imag);
    return z;
}

u=1-2i
v=2-1i
u+v=3-3i

In addition, I wanted to overload += as well:

Complex Complex::operator+=(const Complex& u) {
    Complex z(_real + u._real, _imag + u._imag);
    return z;
}

This however, does not work as expected and the result of u+=v is u=1-2i. Why is that the case?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Gilfoyle
  • 3,282
  • 3
  • 47
  • 83
  • Possible duplicate: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading?rq=1 – Max Langhof Oct 22 '19 at 15:24

2 Answers2

2

Your compound assignment operator creates a new object z instead of changing the original object.

Declare the operator within the class definition like

Complex & operator+=(const Complex& u);

and define it the following way

Complex & Complex::operator+=(const Complex& u) {
    _real += u._real;
    _imag += u._imag;

    return *this;
}

The operator can be defined as a non-class friend function. For example

class Complex {
    private:
        double _real;
        double _imag;

    public:
        Complex();
        Complex(double real, double imag);
        Complex(const Complex& z);

        Complex operator+(const Complex& u) const;
        friend Complex & operator+=(Complex &v, const Complex& u);
};
Complex & operator+=(Complex &v, const Complex& u)
{
    v._real += u._real;
    v._imag += u._imag;

    return v;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • That helped a lot. Why do you return the result by reference? – Gilfoyle Oct 22 '19 at 15:17
  • @Samuel Because that's what `operator+=` is supposed to do. See also https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading?rq=1. – Max Langhof Oct 22 '19 at 15:23
  • @Samuel In C++ opposite to C the assignment operator returns lvalue reference. For example in C++ you can write int x = 1; int y = 10; ( x += y ) *= 10; – Vlad from Moscow Oct 22 '19 at 15:24
1

First of all assign like operators should return reference to assigned value.

Secondly your code should change value of current object.

There are couple solutions:

Complex& Complex::operator+=(const Complex& u) {
    *this = Complex(_real + u._real, _imag + u._imag);
    return *this;
}

Or

Complex& Complex::operator+=(const Complex& u) {
    _real += u._real;
    _imag += u._imag;

    return *this;
}
Marek R
  • 32,568
  • 6
  • 55
  • 140