Search code examples
c++classoperator-overloadingcompound-assignment

Overloading compound-assignment-operator in C++ does not change variable


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?


Solution

  • 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;
    }