copy and assignment operator

someone's asked this before on fb. i found this useful, so i want to ask about this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<conio.h>
struct point
{
float x;
float y;
void operator =(point);
};
void point::operator =(point p)
{
x=-p.x;
y=-p.y;
}
void main()
{
clrscr();
point p={3.0,4.0};
point k=p;
cout<<k.x<<" "<<k.y<<" "<<p.x;
getch();
}


well, anyway, i guess you already know the answer. the code wants to assign and print the negative numbers from k. and it said that this:

 
point k=p;


is not calling the overloaded assignment operator, but instead, the copy constructor. so, if there's any link that explain about this problem? because i tried to search it in this site but haven't found it (just for a few moment actually).
There's nothing really to explain. point a = b; is synonymous with point a(b);, which calls a constructor, not the assignment operator.

If you want to call the assignment operator, you have to put it in a command other than the one which the object is constructed:

1
2
point a;  // construct the object
a = b; // then assign it 



Of course -- that's besides the point that this shouldn't matter. The assignment operator should do more or less the same thing as the copy constructor, only the copy constructor has the potential to be more efficient since it can construct and initialize the object in one go.


Here, this assignment operator is ill advised because it's unintuitive. It does something other than you'd expect.

1
2
3
4
point a, b;

a = whatever;
b = a;  // people would expect a and b to be identical here, but with your operator, they aren't 
Last edited on
Topic archived. No new replies allowed.