-4

My question is that why this->var will automatically pick 12, and obj.var just pick 55? Why this->var is not 55? Is it because that the position it is placed?(I mean this->var+obj.var where this-> is placed in front of the "+" sign) and if I change the code like this: res.var= obj.var-this->var; , it seems that this->var is still 12. So it seems like the cod obj1+obj2, if obj2 is "after" the "+" sign, it is the one which is thrown to the &obj, is that the correct inference? Thanks!

#include <iostream>
using namespace std;
class MyClass {
    public:
        int var;
        MyClass() { }
        MyClass(int a)
        : var(a) { }
        MyClass operator+(MyClass &obj) {//here's my problem
            MyClass res;
            res.var= this->var+obj.var;//here's my problem
            return res; 
        }
};
int main() {
    MyClass obj1(12), obj2(55);
    MyClass res = obj1+obj2;//here's mt problem
    cout << res.var;
}
  • 2
    Welcome to Stack Overflow. The reason why is because operators operate from left to right. So, obj1 (which in the operator+ is `this`) is the left so it would have 12. Think of it like a function call: `obj1.Add(obj2)`. In that scenario, you are passing in `obj2` (which is 55). Same thing is happening here. – Andy Jun 25 '19 at 02:51
  • They are 2 separate objects. `this` in this context refers to `obj1` which holds the value 12, while `var` refers to `obj2` which holds the value 55. –  Jun 25 '19 at 03:05
  • 3
    Also, if this is tripping you up, then I highly recommend getting a [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to help you out. –  Jun 25 '19 at 03:06
  • `obj1 + obj2` is the same as `obj1.operator+(obj2)`. – molbdnilo Jun 25 '19 at 06:33

1 Answers1

1

On c++ all operators have associavity rules. Addictive, multiplicative, shift, logical etc. operators are left right associative. Unary, assignment operators are right to left associative. Therefore, whenever you use left associative operators compiler reads it from left to right like your code.

  • Associativity only matters when there is more than one operator involved (for instance in `3 - 2 - 1`) and is completely irrelevant here. `*this` of a member operator is *always* the left-hand operand. – molbdnilo Jun 25 '19 at 23:39