Overloading operators

Hi I am studying Overloading Operators at class2. Even after I read explanation, I still don't understand the things like 'operator + (const CVector&)' why does it has to be 'const CVector' and add '&'? I also wonder why ' param.x' stands for second value of x (which is 1 in this example). Thank you for reading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 // 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;
}
Const in this case ensures that param can't be changed, which is a good thing. The & means it is a reference to an existing CVector object, and is therefore valid for input to the + operator. If it were a pointer, say, it could actually be a null pointer instead of the expected object instance, which you would never want.
That is not "canonical" op+. It is more natural to have op+ as a non-member that is implemented with a member op+=

If you want to keep the op+ as member, you should make it a const function, because it does not change the object. The foo does not change on line 24 and one could want to calculate sum of const objects.

Why a by reference parameter? The by value parameters are copies, having a copy is not necessary in the operator. Reference is "cheaper" (in certain cases).

The param should not change within the function. The const ensures that the function does not even attempt to change the param (and because param is a reference, change caller's object). Furthermore, if the bar were const object, line 24 were a syntax error without the const in the reference.


Lets rewrite the main() without the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main () {
  // CVector foo (3,1);
  int foo_x = 3;
  int foo_y = 1;
  // CVector bar (1,2);
  int bar_x = 1;
  int bax_y = 2;
  // CVector result;
  int result_x, result_y;
  // result = foo + bar;
    const int & param_x = bar_x;
    const int & param_y = bar_y;
    // CVector temp;
    int temp_x, temp_y;
    // temp.x = x + param.x;
    temp_x = foo_x + param_x;
    // temp.y = y + param.y;
    temp_y = foo_y + param_y;
    // return temp
  result_x = temp_x;
  result_y = temp_y;

  cout << result_x << ',' << result_y << '\n';
  return 0;
}

Comparing the two versions may (or may not) give you new insight.
Topic archived. No new replies allowed.