I have harad time to understand this funciton

first we assign to objects diffrent x and y's but then in the call to operator+
what exactly happen how exactly this function evaluates the two coordinations of x and y of objects a and b

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
#include <iostream>
using namespace std;

  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;
}
That code is rather exact in my opinion. Not const correct though, nor does that compile as is. Your copy-paste-fu requires honing.

The c = a + b; is equivalent to c = a.operator+( b );

One could have equivalent ordinary member function:
1
2
3
4
5
6
7
8
9
10
CVector CVector::sum( const CVector & param ) const
{
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return temp;
}

...
  c = a.sum( b );

Since the data members are public (which is bad habit), one could have a standalone function instead:
1
2
3
4
5
6
7
8
9
10
CVector sum( const CVector & lhs, const CVector & rhs )
{
  CVector temp;
  temp.x = lhs.x + rhs.x;
  temp.y = lhs.y + rhs.y;
  return temp;
}

...
  c = sum( a, b );

Without class stuff you would have:
1
2
3
4
5
6
7
8
9
10
int main() {
  int ax = 3;
  int ay = 1;
  int bx = 1;
  int by = 2;
  int cx = ax + bx;
  int cy = ay + by;
  cout << cx << "," << cy;
  return 0;
}
It's just a vector addition function. It tells the class how to perform an addition given another class of that type.

In this case, it will add two vectors together. In the example, it'll assign the addition of a and b to c.

So,

c = b + a

Essentially means:
c.x = b.x + a.x
c.y = b.y + a.y

So vector C will be (4, 3).
object c is pass to param?
No.

In c = a + b the member function operator+ of object a is called. It takes object b as parameter, so within the functions body the param has been initialized from b.

When the a + b has been evaluated, its return value -- an unnamed CVector object -- is assigned to c.
Topic archived. No new replies allowed.