If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

operator overloading issues!

hey guys
I wrote a simple Complex Class and overload input/output and +/- Operators in it!But there is something that doesn't work correctly!I can print an object of that class but I can't print sum of two object or something like that!

So, you create a Complex object that is initialised to be the sum of the current object and c, as complex numbers, then you return this newly created Complex object named result. However, the return type is Complex&, hence you return a reference to result. But once control leaves this function, result is destroyed, hence the caller receives a reference to an object that no longer exists. That is a Bad Thing.

Furthermore, suppose that the current object is const, e.g.,

Code:

const Complex c1(1, 2);
const Complex c2(3, 4);
Complex c3 = c1 + c2;

The above fails because operator+ is a non-const member function. As such, you should declare operator+ to be a const member function that returns a Complex object by value.

Now, chances are, you would also like to allow:

Code:

Complex c1(1, 2);
const Complex c2(3, 4);
c1 += c2;

If so, then another approach is to overload operator+= as a member function, then declare operator+ as a non-member non-friend function, e.g.,