Overlaoding Operator Help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Overlaoding Operator Help

Hi, I'm really hoping some cone can clarify my misunderstanding. In short, I am stuck on the operator overloading section of solo learn. Below is the code provided by solo code. Question1: Is "MyClass Operator+(MyClass &obj)" a function? Or is it redefining what happens when the "+" operator has two objects next to it so that it is encapsulated? Question2: I don't understand why there is only one parameter. Can't we just pass in two memory addressed of MyClass objects like so: MyClass operator+(Myclass &objOne, MyClass &objTwo) { MyClass res; res = objOne.var + objTwo.var; return res; } Question 3: Some usurer told me that in the statement " res.var = this->var+obj.var; " this.var represents obj1 in int main while obj.var represents obj2 in int main; but, there is only one parameter so I do not understand how this-> refers to obj1. Any help is greatly appreciated. I've been struggling with this for a while now. Thank you for taking the time to read this =) SOLO-LEARN CODE BELOW ------------------------------------------------------ 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 obj(12), obj2(55); MyClass res = obj1 + obj2; cout << res.var; } //output 67 _____________________________________

27th Aug 2019, 7:53 PM
Nitu Roy
Nitu Roy - avatar
1 Answer
+ 1
For the first question, both statements are kind of true. A self defined operator is nothing more than a function looking neat syntax wise. But you also simply assign an additional behaviour to an existing operator, so both aren't wrong. It is not a total redefinition though, but more of an extension to the existing operator. For the second question, yes, you are right, and it is actually recommended to do it the way you mentioned, since binary operators like + are symmetrical and the arguments are not changed in any way. In that case, the operator is not a member function of the class though. Anyway, both solutions are possible here. And for the third question, let's have a look how calling the operator would look like using function syntax: MyClass res = obj1.operator+( obj2 ); Since 'this' refers to the calling object, which is obj1 as can be seen clearly here, it refers to obj1. If there's more, feel free to ask.
27th Aug 2019, 8:06 PM
Shadow
Shadow - avatar