another tut question - classes

Here is the program:

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
32
// vectors: overloading operators example
#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 (1,2);
  CVector b (3,4);
  CVector c;
  c = a + b;
  cout << c.x << "," << c.y;
  return 0;
}


I did some cout on this here:

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


and I can see that x is being passed as 1 and y is being passed as 3; param.x is 2 and param.y is 4. I just cannot see how the program is doing this. Anyone have an idea how to explain this?
I believe it works like this:

1
2
3
4
5
6
CVector CVector::operator+ (CVector param) { //using + operator with a CVector param
  CVector temp; //create a temp vector to return
  temp.x = x + param.x; //make temp.x = the x value of the current vector (left side of +) added to param.x 
  temp.y = y + param.y; //same for y
  return (temp); //return the vector
}
firedraco, you just hit right to the heart of this. I can't believe I didn't understand this on my own - now it seems so obvious. Thank you very much!
No problem :)
Topic archived. No new replies allowed.