How operator oveloading works

Posted by Rasmi Ranjan Nayak on Stack Overflow See other posts from Stack Overflow or by Rasmi Ranjan Nayak
Published on 2012-10-01T09:33:53Z Indexed on 2012/10/01 9:37 UTC
Read the original article Hit count: 231

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about operator-overloading