I have below code
class rectangle
{
//Some code ...
int operator+ (rectangle r1)
{
return(r1.length + length);//Length is the 1st argument of r1, r2, r3
}
};
In main function
int main()
{
rectangle r1(10,20);
rectangle r2(40,60);
rectangle r3(30,60);
int len = r1 + r3;
}
Here if we will see in operator+(), we are doing r1.length + length.
How the compiler comes to know that the 2nd length in return statement belong to object r3 not to r1 or r2?
I think answer may be in main() we have written
int len = r1 + r3;
If that is the case then why do we need to write in
operator+ (....)
{
r1.lenth + lenth; //Why not length + length?
}
Why not length + length? Because compiler already knows from main() that the first length belong to object r1 and 2nd to object r3.
You’re confusing variable names with argument names. In the operator overload, you named your parameter
r1:that means that whatever parameter you pass to
operator +, inside the body of the operator it will be namedr1(regardless of its original name).r1.lengthis the length of the parameter, andlengthis the length of the current object (i.e.this->length).This would just return the double of the current object’s length.
Let’s analyse the code:
The last call is equivalent to
r1.operator+(r3). Inside the operator,lengthrepresentsr1.lengthandr1.lengthrepresentsr3.length. Actually, not evenr3.length, since you’re passing by value, and a copy will be created. The usual syntax would be:Also, adding rectangles doesn’t really make sense, at least how you defined it. It’s not intuitive that adding two rectangles returns the sum of the lengths. It should at least return a different shape.