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+

5th Sep 2016, 3:38 AM
Pranav Dixit
8 odpowiedzi
+ 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.
5th Sep 2016, 5:28 PM
Zen
Zen - avatar
+ 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.
5th Sep 2016, 9:22 AM
Zen
Zen - avatar
+ 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 ->.
5th Sep 2016, 10:47 AM
Zen
Zen - avatar
+ 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.
15th Oct 2016, 2:58 PM
shripad kulkarni
shripad kulkarni - avatar
0
is it compulsory to use "this" while operator overloading
5th Sep 2016, 10:55 AM
Pranav Dixit
0
that means a key word this
30th Sep 2016, 4:37 PM
priyanga
priyanga - avatar
0
yes the keyboard "this"
1st Oct 2016, 1:42 AM
Pranav Dixit
- 1
what is this->var ?
5th Sep 2016, 10:15 AM
Pranav Dixit