You are returning a reference to a temporary object which is really bad.
overload& overload::operator+(overload c1)
You should return a object and not a reference.
By the way, you should almost always overload
operator +=
instead which would return a reference to this and then implement binary
operator +
using that code.
By the way, it make no sense to store integer in a complex number class (and it make no sense to reinvent the well instead of using an existing comple number class). That way, you avoid all those problems. Usually you would write such class only for educationnal purpose.
Anyway, the implementation should look like this:
overload &operator+=(const overload &other)
{
r += other.r;
i += other.i;
return *this;
}
And outside the class definition, you would have:
overload operator+(const overload &lhs, const overload &rhs)
{
overload result(lhs);
result += rhs;
return result;
}
or alternatively
overload operator+(const overload &lhs, const overload &rhs)
{
return overload(lhs) += rhs;
}
As an added benefit, you don't need
friend
declaration and you gain symmetry if you have mixed type expression.
overload a(1, 2);
overload b = a + 1;
overlaod c = 2 + a;
Finally since
operator+=
is defined, then you can write more efficient code when you don't need a new variable for the result.
There are a few other things that might be improved in your code. It could be a good think to read books on how to write Professional grade C++ code. Book like "Exceptionnal C++" are really good.
Also, I don't really understand exactly your problem. it could have beeen a good idea to reduce the code to only the code necessary to show the problem and explain it better.