what calling this function

i have hard time to understand how this particular function work.
in the int main function we assign y and x with two objects. but how the function know which object we intend to "+" operator + get one argument of type
CVector in this case it C know i cant understand the computation itself

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
28
29
30
31
#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;
}
Last edited on
As far as I know the second operand is being passed, like so:
a.operator+(b);
so in reality only "a"passed to the core of the function and" b" is just + to a?
Expression

a + b;

is substituted by the compiler for

a.operator +( b );

As operator + is a member function of CVector and called for object a it has access to all data members of object a.

Logically the call

a.operator +( b );

is equivalent to

operator +( this, b );

where this is a pointer to a.

For example you could write the definition of the operator the following way

1
2
3
4
5
6
CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = this->x + param.x;
  temp.y = this->y + param.y;
  return (temp);
}


Last edited on
Topic archived. No new replies allowed.