-3

Here is a simple example given to illustrate overriding an operator in C++. I don't understand the meaning of the & in 'CVector&' in lines 9 and 12. It doesn't look like they are passing the address of a CVector, it seems like the & can be ommitted, since the operator is just taking in a CVector as a parameter.

#include <iostream>
using namespace std;

class CVector {
  public:
  int x,y;
CVector () {};
CVector (int a,int b) : x(a), y(b) {}
CVector operator + (const CVector&);
};

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

int main () 
 {
   CVector foo (3,1);
   CVector bar (1,2);
   CVector result;
   result = foo + bar;
   cout << result.x << ',' << result.y << '\n';
   return 0;
  }
fdzsfhaS
  • 79
  • 10
  • It's pass by reference. So it's just like passing in the address, except you don't have to dereference the variable like a pointer to use it. – spektr Dec 07 '15 at 20:37
  • 2
    If you don't know about references in C++, you might need to back up from operator overloading and go more basic on what you are learning. – crashmstr Dec 07 '15 at 20:41

2 Answers2

2

Those are references. They're a pretty fundamental concept in C++ and I don't think I can do justice to them in this short space. I'd recommend consulting a C++ tutorial or reference to learn more about them, preferably in a context that doesn't also involve other complex concepts like classes.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
1

Whenever you see & in C++, if it is with a parameter of a method, that means that the variable being argued to the method will be passed by reference, and with a standalone variable, it is referencing the address of the variable storage.

m_callens
  • 6,100
  • 8
  • 32
  • 54