-5

Could somebody help me understand this code. I am lost with it because the professor just flew through it in class

class OpClass
  {
   private:
     int x;
   public:
     OpClassoperator+(OpClass right);
  };
OpClass OpClass::operator+(OpClass r)
{  OpClass sum;
sum.x = this->x + r.x; 
// or  sum.x = x + r.x;
return sum;
}
blackstreet23
  • 17
  • 1
  • 4
  • BTW, the professor (or you) made a mistake in the function signature. As you showed it isn't wrong syntax but does fail to accomplish what is almost certainly intended. It should be `OpClass operator+(OpClass const& r) const` – JSF Dec 14 '15 at 00:02

1 Answers1

3
class OpClass
{
private:
  int x;
public:
 // declare operator+ - i.e. OpClass + OpClass
 // this function will be returning a copy since the expression
 // z = x + y does not modify x or y
 OpClass operator+(OpClass right); // should really be const!
};

OpClass OpClass::operator+(OpClass r)
{  
  // this part is actually garbage.
  OpClass sum;
  sum.x = this->x + r.x; 
  // or  sum.x = x + r.x;
  return sum;
}

and here's how it's done properly:

class OpClass
{
private:
  int x;
public:
 // always perform binary operations in terms of +=, -=, *= etc
 OpClass& operator+=(const OpClass& r) {
   x += r.x;
   return *this;
 }

};

// define binary operators in terms of unary

OpClass operator+(OpClass l, const OpClass& r)
{
  // note that the l argument is implicitly a copy
  l.x += r.x;
  return l;
}  
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • What "*this" is? why you did not return x? – blackstreet23 Dec 14 '15 at 00:22
  • and when you define binary operators in terms of unary. Why did you have an object l when you could use the x directly from the class? – blackstreet23 Dec 14 '15 at 00:24
  • 1
    Notice the choice RicharHodges made to declare `operator+` outside the class. That allowed the left operand to be passed by value, so it can be used in place of the temporary in which the result is assembled. I don't agree with that choice (especially in C++11) but it had a purpose (in some cases and before C++11) – JSF Dec 14 '15 at 00:28