How operator oveloading works
- by Rasmi Ranjan Nayak
I have below code
class rectangle
{
.....
.....//Some code
int operator+(rectangle r1)
{
return(r1.length+length);
}
};
In main fun.
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 writeen
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? Bcause compiler already knows from main() that the first length belong to object r1 and 2nd to object r3.