Overloading =operator [Beginner]

Hello,

In the tutorials there is a function described to copy an object, and the code is as follows:

CVector& CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
return *this;
}

However, I tried this code and after compiling I got some errors. Thereafter I changed the code into this:

CVector CVector::operator= (const CVector param)
{
x=param.x;
y=param.y;
return *this;
}

And after copying in the main an object (e.g. "a = b;"), the program worked smoothly. Now I don't understand why there is in the tutorial made use of the reference operator (&) in the declaration of this function, because I think the function returns an object (*this) and not a reference to an object. Also, I think you don't pass a reference as parameter when you copy an object, but you pass the object itself.

Can anyone make one and other clear to me?

Best regards,

Bart
The problem with your version is that it's producing two temporary copies (one for the parameter and another for the return value). For small objects like this one, this is not much of a problem, but if you do that with larger objects, it can be a serious slow-down.

this is a pointer to the object that calls the method. Therefore, *this is the object itself. If the function says it returns a reference and you return *this, you're returning a reference to the object.

If you got any errors, it wasn't from that method.
You should also note that you don't even need to define operator= for the above class since all it does is a member-wise copy. By default the compiler gives you a member-wise copy. operator= should only be defined for classes that cannot simply be member-wise copied (typically classes with pointers are this way, because often times you want to take a deep copy of the pointer).

Topic archived. No new replies allowed.