what exactly does this Overloading represent ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

what exactly does this Overloading represent ?

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; } how on earth does a SINGLE parameter in the Overloaded operator work for TWO different objects ?! please clarify

28th Dec 2017, 6:46 PM
Muhammad Yasir
Muhammad Yasir - avatar
3 Answers
+ 6
The operator+ you declared is a method, so as I said, it has one more parameter than you wrote : the instance on which it is called. Doing a + b is equivalent to a.operator+(b) which has a (this) as an implicit parameter and b as an explicit parameter
4th Jan 2018, 7:41 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
In your example, it does not work. For it to work, you need : MyClass::operator+ instead of : operator+ Instead of that, you can declare it in directly in the class so that you avoid using "MyClass::" As operator+ is declared as a method, the first parameter (which is the object on which it's called) is omitted
28th Dec 2017, 7:03 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
I should have posted the whole code, here it is; 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; } now that we took care of your Scope Resolution Operator, can you please explain how exactly does the '+' sign overloading works What i have trouble understanding is ... the overloading function takes only a SINGLE argument, the 'second' object (obj2) in this case. so how does the 'first' object (obj1) invoke the SAME overloading function when it is not included in the argument list ? what tethers obj1 to the overloaded function ? i am having trouble understanding that part of the concept !
3rd Jan 2018, 11:59 PM
Muhammad Yasir
Muhammad Yasir - avatar