1

Not able to understand a block of code in below given program. Especially the variable, temp which has return type as the complex(the class name) and when we return the variable, temp where it gets returned to? That is return(temp); in the program.

The Program

#include <iostream>
using namespace std;
class complex
{
public:
    complex();//default constructors
    complex(float real, float imag)//constructor for setting values
    {
        x = real;
        y = imag;
    }
    complex operator +(complex);
    void display(void);
    ~complex();

private:
    float x;
    float y;

};

complex::complex()
{
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
complex complex::operator+(complex c)
{
    complex temp;
    temp.x = x + c.x;
    temp.y = y + c.y;
    return(temp);
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
void complex::display(void) {
    cout << x << "+j" << y << "/n";

}

complex::~complex()
{
}


int main()
{
    complex C1, C2, C3,C4;
    C1 = complex(1, 3.5);//setting of first number
    C2 = complex(2,2.7);//setting of second number
    C4 = complex(2, 5);

    C3 = C1 + C2+C4;//operator overloading
    cout << "C1 = ";
    C1.display();
    cout << "\n C2 = ";
    C2.display();
    cout << "\n C4 = ";
    C4.display();
    cout << "\n C3 = ";
    C3.display();

    system("pause");

    return 0;


}
  • Unrelated to your problem, but with [the generally bad `using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) then you should consider to *not* name your class the same as [the standard `std::complex` class template](http://en.cppreference.com/w/cpp/numeric/complex). – Some programmer dude Nov 11 '17 at 05:20
  • As for your problem, if we look at the usage of the `+` operator, lets say we have (the more simple) `C3 = C1 + C2`, then that's the same as `C3 = C1.operator+(C2)`. Does that help you? – Some programmer dude Nov 11 '17 at 05:24

1 Answers1

0
complex C5;
C5=C1+C2;

means

C5=C1.operator+(C2)

equivalent to

complex temp;
temp.x = x + C2.x; /* x=C1.x*/
temp.y = y + C2.y; /* y=C1.y*/
C5=temp;
Arash
  • 2,114
  • 11
  • 16