Operator overloading confusion

Regarding the first example in the following article:

http://www.cplusplus.com/doc/tutorial/classes2/

more specifically, this piece of code:

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


The param.x and param.y are added to... x and y? Which x and y are these exactly? Whose instance of the class do they belong to and what's the logic behind it?

Thanks.
Last edited on
Which x and y are these exactly?

The ones belonging to the object whose member function is being called.

You could write
1
2
temp.x = this->x + param.x;
temp.y = this->y + param.y;

to the same effect.
And what object is that? I'm still confused so let me take this step by step:

a,b,c are declared as instances of the CVector class (c doesn't have any values for its constructor so c's x and y are going to be garbly gook, right?):
1
2
3
 CVector a (3,1);
 CVector b (1,2);
 CVector c;


c gets the value of a+b so it's using the overloaded operator +
1
2
3
4
5
6
7
8
 c = a + b;
//....
CVector CVector::operator+ (CVector param) {
  CVector temp;
  temp.x = x + param.x;
  temp.y = y + param.y;
  return (temp);
}


CVector gets instanced again as temp (again, temp's x and y are not initialized with some specific value)

So the only x and y values that you know the value of is a's and b's.

cout << x << " " << y; prints out "3, 1" and cout << param.x << " " << param.y; prints out "1,2".

The "1,2" I get (it's b that has been "passed" from the main function in c = a+b) but I don't get how "3, 1" aka a.x and a.y got there...
a+b is just another way to write a.operator+(b) in this case. a's member function is being called.
Thanks a lot, I get it now! Just had to look at the operator the same way I would look at a function (which basically is the same thing I guess).
Topic archived. No new replies allowed.