0

res.var= this->var+obj.var;

res.var = var + obj.var;

both work same so what the benefit of using this keyword Here is my code

#include <bits/stdc++.h>
using namespace std;
class MyClass {
 public:
  int var, v;
  MyClass() {}
  MyClass(int a, int b) 
  : var(a), v(b) { }
  MyClass operator+(MyClass &obj) {
   MyClass res;
   res.var = this->var + obj.var;
   res.v = v + obj.v;
   return res; 
  }
};

int main(){
    MyClass ob(12, 12);
    MyClass ob1(55, 56);
    MyClass res = ob + ob1;
    cout << res.var << " " << res.v;
}

can anyone explain me the benefit of this keyword in operator overloading

  • 3
    Does this answer your question? [Is there any reason to use this->](https://stackoverflow.com/questions/577243/is-there-any-reason-to-use-this) or [When should I make explicit use of the `this` pointer?](https://stackoverflow.com/questions/993352/when-should-i-make-explicit-use-of-the-this-pointer) – user17732522 Feb 25 '22 at 12:49

1 Answers1

2

It's there for clarity: it has absolutely no effect on the generated program.

Some folk prefer (*this). for even better symmetry.

Occasionally you do need to use this to disambiguate from a local variable or even another token; the latter can occur when working with templates and some compilers don't follow the rules properly.

Note that you should pass const MyClass& obj else anonymous temporaries can't bind to your overloaded function: an expression like ob1 + ob2 + ob3 would not compile as you have it.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483