1

This is my main function:

 int main(){
     Complex c1(1.0, 5.0);
     Complex c2(3.0,-2.0);
     Complex c3(1.0, 2.0);
     cout << "c1 + c2 + c3 = "
         << c1 + c2 + c3 << endl;
     return 0;
 } 

This is the function I use to add up the required numbers

Complex& operator+(const Complex & x, const Complex & y){
    Complex c;
    c.a = x.a + y.a;
    c.b = x.b + y.b;

    return c;

}

a and b are private double variables in my class.

On running my program, I seem to get the output as 1+2i ie(c3) and it only seems to work properly when I add only 2 objects. Is there any way I can tweak my existing code to allow it to work for up-to n terms?

Raindrop7
  • 3,889
  • 3
  • 16
  • 27

1 Answers1

3

Your operator + returns a reference to the local variable c, which gets destroyed after it is done. Any further use of the result leads to undefined behavior. You need to return a value, so it gets copied (or a rvalue), but not a reference:

Complex operator+(const Complex & x, const Complex & y) {...}

Aganju
  • 6,295
  • 1
  • 12
  • 23