3

This is excerpted from one of the c++ tutorials:

// vectors: overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);
}

int main () {
  CVector a (3,1);
  CVector b (1,2);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}

In the operator overloading function, it creates a local var temp then returns it, I am quite confused, is this the right way?

qed
  • 22,298
  • 21
  • 125
  • 196

2 Answers2

5

"is this the right way?"

Yes it is. Note that it is not local variable, but a copy of local variable that is actually returned, which is perfectly valid and right thing to do. Be cautious about returning local variables while returning by pointer or reference, not while returning by value.

LihO
  • 41,190
  • 11
  • 99
  • 167
  • Perhaps such operation can cause undefined behavior. For instance, if class stores a pointer to some string which is allocated in constructor and if it has only default copy constructor. – Michael Nov 09 '13 at 22:17
  • @Michael: That is however not this case and quite unrelated to this matter. – LihO Nov 09 '13 at 22:22
  • Ok. Then using class described by the following link will be alright here: http://stackoverflow.com/questions/3278625/when-do-we-have-to-use-copy-constructors ? – Michael Nov 09 '13 at 22:24
1

Yes, because it's returned by value. Had the function had the signature that follows, it would not have been correct:

CVector& CVector::operator+(CVector param);

By the way, a more efficient implementation would look like:

CVector CVector::operator+(const CVector &param) const;
Kijewski
  • 25,517
  • 12
  • 101
  • 143
MDSL
  • 21
  • 1