Overloaded operators Help!

Hi, can someone explain me line by line what the compiler is doing?

I don't understand how the = operator swaps the (x,y) of v1.

The output was ( 8,4 )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #include <iostream>
using namespace std;
class V {
public:
	int vec[2];
	V(int a0, int a1) { vec[0]=a0; vec[1]=a1; }
	V(void) { vec[0]=vec[1]=0; }
	V& operator=(V &arg) {    // what does (V &arg) do? I thought & was used for reference purposes. Explain me please!!
		for(int i = 0; i < 2; i++)   // what is this for? and what does it do?
			vec[i] = arg.vec[1 - i];   // what is this for? and what does it do?
		return *this;
	}
};
int main(void) {
	V v1(4, 8), v2;
	v2 = v1;
	cout << "(" << v2.vec[0] << ", " << v2.vec[1] << ")" << endl;
	return 0;
}
On the first iteration of the loop, i is zero and 1-i is 1, so this copies from arg.vec[1] to this->vec[0].
On the second iteration of the loop, i is 1 and 1-i is zero, so this copies from arg.vec[0] to this->vec[0]
Then i becomes 2 and the loop ends.

note that operator= should better take a const V& arg, or you wouldn't be able to call it with a temporary.
Line 7: Don't write V(void) -- instead write V().

Lines 8-12: Line 10 is a problem, because an assignment operator is supposed to make a copy of its argument. It should look like this:

1
2
3
4
5
	V& operator=(const V &arg) {
		for (int i=0; i<2; i++)  // Loop, i=0,1,... while less than 2
			vec[i] = arg.vec[i];  // Copy corresponding element
		return *this;
	}

The problem with your line 10 is that it is not making a copy of its argument, but doing something different.

For example, suppose you have the following code:

1
2
3
4
5
6
7
8
int main() {
	int x = 5;
	int y;

	y = x;

	cout << y << "\n";
}
7

What would you expect the output to be? Does it make sense that the output is "7"?

No, of course not. The output should have been "5".

Likewise, when assigning one object to another, the objects should have the same values.

If you want to do something odd, like swap the first and last elements in a 2D vector, then that should be a member function:

1
2
3
4
5
6
7
8
class V {
public:
	...
	void reverse() {
		int temp = v[0];
		v[0] = v[1];
		v[1] = temp;
	}

Now in your code, you can do it explicitly:

1
2
3
4
5
int main() {
	V a( 3, -7 );
	a.reverse();
	cout << "(" << a.vec[0] << ", " << a.vec[1] << ")" << endl;
}
(-7, 3)

Yay!

Hope this helps.
Last edited on
Topic archived. No new replies allowed.