Why do we use this keyword in operator overloading? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

Why do we use this keyword in operator overloading?

So I'm a beginner c++ programmer and when I read the sololearn tutorial, it said this keyword is important in operator overloading. I don't know why we use this keyword. I tried without using this keyword and got the output I expected.

14th Sep 2021, 11:47 PM
Overwatch
Overwatch - avatar
1 Respuesta
+ 2
#include <iostream> using namespace std; class MyClass { public: int var; MyClass() {} MyClass(int a) : var(a) { } MyClass operator+(MyClass &obj) { // here obj has the value of obj2. MyClass res; res.var= this->var+obj.var; // as the passed argument can access its variable var directly, so obj.var has the value of obj2 // but how will you access obj1 value for that "this" keyword is being used here. // so res.var will contain obj1+obj2. return res; } }; int main(){ MyClass obj1(123),obj2(145); MyClass result= obj1+obj2; // here result also has. its own var variable // obj1+obj2 will be pronounced as obj1 called + operator and passed obj2 as an argument. cout<<result.var; return 0; }
15th Sep 2021, 1:29 AM
HK Lite
HK Lite - avatar