2
votes

See edit at the end

I am trying to overload the + operator in C++ to allow me to add two complex numbers. (add the real and add the imaginary).

Here is my overloaded function:

ComplexNum operator+(ComplexNum x, ComplexNum y){
ComplexNum result;
result.real = (x.getReal() + y.getReal());
result.imag = (x.getImag() + y.getImag());

return result;
}

My Complex number constructor takes in two ints and assigned the first to int real and second to int imag.

When I try add them:

ComplexNum num1 = ComplexNum(1,1);
    ComplexNum num2 = ComplexNum(2,3);
    ComplexNum num3;
    num3 = num1 + num2;
    printf("%d",num3.getReal());

I get 0 as a result. The result should be 3 (the real parts of num1 and num2 added)

EDIT: I figured out what was wrong. I had .getReal() and .getImage() returning double.

3
Are you aware of the std::complex template? - CB Bailey
You need to post the code for all of your ComplexNum class. In particular the definition of the data members and your copy constructor and copy assignment operator (if user defined). - CB Bailey
Have you by any chance got a copy constructor or assignment operator defined? If so they may be wrong - the defaults should work OK. - anon
I figured out what was wrong, should I just delete the question? - irl_irl
If you figured out the problem, post it as an answer so that it may help others in the future. - jalf

3 Answers

3
votes

Since the arguments of operator+ are declared as values, not references, they will be passed by copy, so if the copy-constructor of ComplexNum doesn't work, that could cause x and y to have a real part of 0.

It's also possible that the addition works, but you lose the real part when you invoke the assignment operator of num3.

Or maybe it's simply the getReal() method that is broken.

1
votes

It looks to me like either your copy constructor or assignment operator is broken. Could you post the code for those as well?

0
votes

On a side note: The canonical way to implement operator+ is as a free functions on top of the member operator+=. (The same goes for -=, *= etc., BTW.) For any type T, it should look like this:

T operator+(const T& lhs, const T& rhs)
{
   T tmp(lhs); 
   tmp += rhs; //invoke +=
   return tmp;
}

The rationale for this convention (which, IIRC, Stroustrup attributes to Koenig):

  • + and += (and - and -= etc.) do nearly the same; in order to avoid redundancy, one should be implemented on top of the other
  • += needs to change the left operand, so it should be a member; + leaves its arguments alone, so it should be a free function
  • it's usually easier and/or more efficient to implement non-members on top of members; this case is no exception