Here 3 variations of the overloading of addition operator (+) are given.
Which variation should I use and why?
class MyClass {
int myInteger;
double myDouble;
public:
MyClass(int i, double d) {
myInteger = i;
myDouble = d;
}
// Variation - 1
//--------------
MyClass operator +(MyClass rhsObj) {
return MyClass(this->myInteger + rhsObj.myInteger, this->myDouble + rhsObj.myDouble);
}
// Variation - 2
//--------------
MyClass &operator +(MyClass &rhsObj) {
rhsObj.myInteger = this->myInteger + rhsObj.myInteger;
rhsObj.myDouble = this->myDouble + rhsObj.myDouble;
return rhsObj;
}
// Variation - 3
//--------------
MyClass &operator +(MyClass &rhsObj) {
this->myInteger = this->myInteger + rhsObj.myInteger;
this->myDouble = this->myDouble + rhsObj.myDouble;
return *this;
}
};
int main() {
MyClass objOne(10, 10.5);
MyClass objTwo(20, 20.5);
MyClass objThree = objOne + objTwo;
}
What should be the case of Assignment Operator (=)? Which variation should it use?