-1

In this code, why put & in const CVector& param ???

we can use it as follow

c = a + b;
c = a.operator+ (b);

in the second statement, b is not CVector& type, so that is why I am confused.

// overloading operators example

#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;
}
creack
  • 116,210
  • 12
  • 97
  • 73
Jianchen
  • 303
  • 2
  • 13

3 Answers3

2

As you do not want your operand to be modified by the operation, you have two solutions:

  1. Send a copy of your object so that the original stays untouched
  2. Send it as a const reference: the const keyword prevent your from modifying the object and the reference allows you to pass the object without a copy.
creack
  • 116,210
  • 12
  • 97
  • 73
1

Cause you are not operating (modifying its properties) on the second vector, You are just reading from it. By using & sign you make sure it is passed by reference which works efficiently if second vector was a big data structure, such as 1000*1000 matrix.

macroland
  • 973
  • 9
  • 27
0

You use reference to avoid copying object and const to indicate that object will not be modified.

Eric Fortin
  • 7,533
  • 2
  • 25
  • 33