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.
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.