Operator = overloading

let's say I have this:
1
2
3
4
5
6
7
8
9
10
struct coor
{
int x;
int y;
COORD operator=(coor c)
{
COORD C={c.x,c.y}
return C;
}
}


and I needed to do:
1
2
coor c={0,0};
COORD C=c;


I could add operator overloading to coor, but how do you do that to return to left side?
Last edited on
Operator = must assign values to members of the object itself. The return value is there just to make a = b = c and similar things work. In your case it is irrelevant. Also, if you have A = B, the = defined in A will be used and if you have B = A, the = in B is used.
What you need is to write a = in COORD that takes coor parameter and updates members of this.
Well the COORD is defined in windows.h, that's why I posted here...
Where it is declared is of no relevance, it doesn't make the operator= implementation any more correct.
What you probably want is a COORD conversion operator and a conversion constructor.

And the following does not call operator=:
COORD C=c;
It calls a matching constructor.
Last edited on
As Athar said:

1
2
3
4
5
6
7
8
9
struct coor
{
 //...
 operator COORD()const
 {
   COORD ret ={ x, y};
   return ret;
 }
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
struct coor
{
int x;
int y;
         coor() { x = 0 ; y = 0 ; }
         void operator=(coor c)
         {
               x = c.x;
               y = c.y; 
          }
};


I suppose this is the right way to do it ..
there should be no return type and secondly the value should be assigned to the variable from the variable that is passed in the object .
Also you will need constructor on this to initialize the variable .
@bluecoder, I'm fairly certain operator = should return *this and have a return type of ThisClass&.
thx for replies!
you are right .. @hamsterman ..upon the second thought , operator should return the this pointer .
thanks for pointing out ..
Isn't that just a convention?
Well, that is what default operators do. Although, having taken a look at the standard, I don't think it minds what you do with your own = operator.
Actualy, the operator= MUST return *this for things like this: a=b=c=d to work!
Of course, but as I said, that's a convention.
Topic archived. No new replies allowed.