I am new to C++ and trying to learn it the proper way. In particular, I am practicing a simple assignment operator overloading in the following class
class Point { public: int x; int y; Point():x(0),y(0){}; Point operator=(Point Y); }; The assignment operator being:
Point Point::operator=(Point Y){ Point temp; temp.x = Y.y; temp.y = Y.x; std::printf("temp has coordinates %d, %d\n",temp.x,temp.y); return temp; } When I have the following in main, I don't understand why I don't end up with B.x = 0, B.y = 3.
int main() { Point A; Point B; A.x = 3; B = A; std::printf("B has coordinates %d, %d\n",B.x,B.y); return 0; } I know I am not using the implicit this pointer to B in my case, and the code does superfluous copies and there is a better way to do it via references as the parameter type. But temp has the fields: temp.x = 0, temp.y = 3, so why doesn't B end up with them?
B. You assigned the values fromAtotempinstead. Why did you do that? In the assignment operator you set destination member to the value of source membersoperator=will do the right thing. Do you need thestd::printfside-effect?Pointif the swap x/y is intended.Point Point::operator=(Point Y), is there a reason you pass the input by value (making a copy)? Or did you intend to pass by reference? Also when you do operator overloading it is customary to do it in such a way that there are "no surprises"... swapping x and y is very very surprising