0

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

Keyur Golani
  • 573
  • 8
  • 26
  • 1
    You didn't mention a pretty important ingredient: Code 1 is only for *member overload*, and in that case the left-hand-side is `*this`. Code 2 is only for *non-member overload* and in that case the left-hand-side is `a`. – M.M Apr 05 '16 at 23:20
  • 1
    Specifically see [this answer](http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729) for deciding whether to use member or non-member – M.M Apr 05 '16 at 23:22
  • Sorry, just cropped up an example to explain my doubt. Didn't craft it well. Also a newbie in the C++ world. Just learning. Can you suggest the right edits please? – Keyur Golani Apr 05 '16 at 23:23
  • Ok. Will refer the link for the whole understanding. Thanks a lot for the info. – Keyur Golani Apr 05 '16 at 23:25

0 Answers0