The operators are like a member function of the class rectangle but with another call format.
You can also call as a function int len = r1.operator+(r3); as suggested by other users.
So, when you write an operation using an operator from your class, the compiler tries to match the call with some of the given operators; in your call:
int len = r1+r3;
The compiler looks for an operator+ that returns something that could be put into an int and receives a rectangle as a parameter and it found your int operator+(rectangle r1) function; then calls this function with the r3 parameter and returns the int result.
The parameter given to the int operator+(rectangle r1) function is a copy of r3 so, it is why is operating over r3 and not over r1 or r2.
This is no mentioned in the question, but I think is worthy to mention:
It seems that your operator+ doesn't suits the model that operators follows usually, if you're going to add a rectangle and getting an object different from rectangle from the operation it doesn't looks like an operator; I think you must think about what you want to get and what a summatory of rectangles is.
As a binary operator it usually gets and returns the same kind of object (in order to use it in operations chain) and must be const because it doesn't changes the object itself:
class rectangle { // Reference in order to avoid copy and const because we aren't going to modify it. // Returns a rectangle, so it can be used on operations chain. rectangle operator+(const rectangle &r) const { rectangle Result; // Do wathever you think that must be the addition of two rectangles and... return Result; } }; int main() { rectangle r1(10,20); rectangle r2(40,60); rectangle r3 = r1 + r2; // Operation chain rectangle r4 = r1 + r2 + r3; rectangle r5 = r1 + r2 + r3 + r4; // Is this what you're looking for? int width = (r1 + r3).width(); int height = (r1 + r3).height(); }
If it is an unary operator the parameter and return value must be of the same type too, but the return value must be the object that takes part of the operation:
class rectangle { // Reference in order to avoid copy and const because we aren't going to modify it. // Returns a rectangle, so it can be used on operations chain. rectangle &operator+=(const rectangle &r) const { // Do wathever you think that must be the addition of two rectangles and... return *this; } }; int main() { rectangle r1(10,20); rectangle r2(40,60); rectangle r3 = r1 + r2; // Weird operation chain, but it's only an example. rectangle r4 = (r1 += r2) += r3; rectangle r5 = (r1 += r2) += (r3 += r4); }
length + lengthrefer to different lengths. That special magic wouldn't even work in general - the operator implementation could be nontrivial.