0
can anyone plz explain me this program step by step?#include <iostream> using namespace std; class MyClass { public: int var; MyClass() { } MyClass(int a) : var(a) { } MyClass operator+(MyClass &obj) { MyClass res; res.var= this->var+obj.var; return res; } }; int main() { MyClass obj1(12), obj2(55); MyClass res = obj1+obj2; cout << res.var; }I am not getting the part inside operator+
8 ответов
+ 3
How else would you refer to the left operand without using "this"? Also, this is not specific to operator overloading. The "this" pointer is specific to OOP and is always available in any of your method to refer to the object the method was called on. Think of it as an implicit first argument of any method.
Btw, obj1+obj2 is basically obj1.operator+(obj2). The aim of operator overloading is precisely to lighten the synthax.
+ 2
The operator+ part overloads the + operator so it can be used with objects of class MyClass. Here, it returns a new object of MyClass with its var as the sum of their var attributes.
+ 2
"this" is a pointer to the object you called the method on (when inside the method). And this->var is its var attribute. Dot notation is used when manipulating the objects themselves (obj.var for example). With pointers, you need to use ->.
+ 1
pranav for the question on what is operator + ..it's overloading that means when u have two classes of type MyClass you can simply add them. the content of member function operator+ tellz what exactly is to be done when you encounter addition of two variables with type MyClass.
0
is it compulsory to use "this" while operator overloading
0
that means a key word this
0
yes the keyboard "this"
- 1
what is this->var ?