some help with overloading operators

Hi all,
It's getting interesting now, but also more difficult. Please have a look at the following example for overloading operators in order to create a vector addition operation:

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
// 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 (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}


Can somebody give me a detailed explanation of lines 17 and 18? I have also some trouble with line 15, to be honest. I ran a debug version of the code and could follow the compiler steps quite good, but it eludes me what happens really in these lines (I mean where the variables from a, b are inserted etc., that sort of stuff).
Last edited on
Line 15 - contains operator-function declaration

In lines 16 a vector CVector temp is created. Then in lines 17 and 18 its members x and y are set to sum of values of x and y of the original object and of the object that is passed as argument to the operator-function.
So the original object is x, y, OK. But where comes the object "param" from?
The expresssion

a + b;

is equivalent to expression

a.operator +( b );

So param is a copy of b because b is passed to the operator-function by value. So in fact the following is done

1
2
CVector param = b;  // here the copy constructor is called
CVector temp; // here the default constructor is called 


then the sum of two vectors, a and param, is calculated

1
2
temp.x = a.x + param.x;
temp.y = a.y + param.y;
Last edited on
So, all the effort is essentially to construct the part "+ param.x(y)"? which fulfils our wish for vector addition? If that's it, I may have understood now. But it also confirms I lack a certain talent for C++ ;).
Thank you for the illuminating explanations
Last edited on
Topic archived. No new replies allowed.