MyClass operator+(MyClass &obj) no entiendo el & si no esta en el main para llamar ala funcion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

MyClass operator+(MyClass &obj) no entiendo el & si no esta en el main para llamar ala funcion

No entiendo porque en la sobrecarga se pone '&' antes como parametro para el objeto si no tiene sentido si se pasara por referencia deveria ser MyClass operator+(MyClass *obj) {} Ejemplo que vi en sololearn class MyClass { public: class MyClass { public: int var; MyClass() {} MyClass(int a): var(a) { } MyClass operator+(MyClass &obj) {} }; Equivalencia, puse obj y funciono igual int var; MyClass() {} MyClass(int a): var(a) { } MyClass operator+(MyClass obj) {} };

5th Jan 2023, 11:47 AM
Hector Mamani
Hector Mamani - avatar
5 Answers
+ 2
MyClass operator+( MyClass& obj ) Here the overloaded `+` operator accepts MyClass instance reference, and work using the actual instance that were passed in as argument. Any change (if any was made) on the reference argument will reflect on the actual instance being passed as argument. ______________________________________ MyClass operator+( MyClass obj ) Here the overloaded `+` operator accepts MyClass instance, makes a copy of it, and works on the copy. The actual instance passed as argument will not be affected by any change (if any was made) to the copy.
5th Jan 2023, 12:45 PM
Ipang
+ 2
Ipang when we pass by reference we usually use the * instead of the &. That's why it's trycky I guess
5th Jan 2023, 12:56 PM
Kenobi
Kenobi - avatar
+ 2
Ipang Oh I get it, thanks for the article
5th Jan 2023, 1:45 PM
Kenobi
Kenobi - avatar
+ 1
I guess it's because you have to set an object as parameter which is the adress the object you call
5th Jan 2023, 12:06 PM
Kenobi
Kenobi - avatar