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?

4
  • 3
    We could give a more meaningful answer than "yes" if you explain what you're confused about. Commented Nov 9, 2013 at 22:05
  • If you don't count the fact that operator+ is typically implemented in terms of operator+=. Commented Nov 9, 2013 at 22:07
  • Are the parentheses in return (temp) necessary? Commented Nov 9, 2013 at 22:49
  • @qed No, they are unnecessary noise. Commented Nov 17, 2013 at 16:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: That is however not this case and quite unrelated to this matter.
Ok. Then using class described by the following link will be alright here: stackoverflow.com/questions/3278625/… ?
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;

1 Comment

In short, pass by reference, return by value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.