I was learning operator overloading on C++. I was wondering how do we exactly determine object at which side of the operator is calling the operator overloaded method and what side of objects gets passed as an argument.
For an example, below code accepts an int
and returns an int
which is a commonly known knowledge.
int operator=(const int a) {
foo(a);
int x = a;
return a;
}
But the binary + operator can be overloaded in two ways
Code 1
ReturnType operator+(T a) {
T x;
foo(a);
x = this -> a + a;
return x;
}
Or
Code 2
ReturnType operator+(T a, T b) {
T x;
foo(a);
x = b + a;
return x;
}
Now when we call JohnDoe = John + Doe
, John + Doe
produces the ReturnType
from the code. And a John
could become the calling object and Doe
could become the passed argument calling Code 1 or John
and Doe
both could become the passed arguments calling Code 2.
So how do we decide which way from the above two, to implement the operator overloading?
The +
operator is just an example. I want to understand the general way operator overloading works. How is it decides that which side of the operator will call the method, which side of the object will be passed to the argument and which side of the operator will be the second argument.
I did find a good reference to all the operators overloaded. But it didn't help me understanding the general terminology that I want to understand. http://www.drbio.cornell.edu/pl47/programming/TICPP-2nd-ed-Vol-one-html/Chapter12.html