complex operator+(complex a2) // why this argument is used please explain
{
complex a; //what is the need of this
a.r=r+a2.r; //and how it is being done
a.i=i+a2.i; //this one too
return a;
}
Ans 1. complex operator+(complex a2)
The complex
is specifying that the return type is going to be of the type class complex
. complex a2
specifies that the operator is going to be used with an object of class complex
.
Ans 2. complex a;
This is required to do a temporary operation with the objects and data members of the class complex. Think of it like a temp
variable you introduces to add 2 numbers in a function and return it later on.
Ans 3. a.r=r+a2.r;
Okay now that you have cheated a temporary object of the class complex you say storing the sum of a2
's r
and the the object that called this overloading function's r
and storing it into the temporary object's r
.
Ans 4. a.i=i+a2.i;
Same as above.
Then you return
the temporary object a
with the calculated sums of r
and i
. Note that the type
of a
is of the class complex
and so the return type was specified as complex
in line 1.
You will understand it better if you also see the operator being used in the main()
function.
complex x,y,z;
x=y+z;
Here x
will get the value of the temporary object a
. The calling variable is y
and a2
will receive z
. It is like calling +
here like
x = y.overloaded_plus(z) // only for explanation