Skip to main content
gamedev.net
🔒 Locked

operator *=, +=, -=, etc overloading

Started by Digicube 5 replies 300+ views
Original Post
Digicube
Digicube
Hi, Can anyone explain to me how assignment operator overloading works? For example if I did this: Class Vector { ... Vector operator+=(Vector otherV); point[3]; ... } Vector Vector::operator+=(Vector otherV) { Vector newVector; newVector.point[0] = otherV.point[0]; newVector.point[1] = otherV.point[1]; newVector.point[2] = otherV.point[2]; return newVector; } and If I use it like this: Vector v1(1,1,1), v2(2,2,2); v1 = v2; "v1" will not change. I know this doesn''t work, but why doesn''t it work? The correct way would be directly modify the "point" member instead of creating a new vector variable then returning it. Any thoughts? Thanks.
fallenang3l
fallenang3l
The correct syntax for overloaded = is:
class_name & operator =(const class_name &)

so your declarations should look like this:

  
class Vector {
public:
Vector & operator =(const Vector & v);
};

Vector & Vector::operator =(const Vector & v)
{
if (this == &v) // self-alias check

return *this;
point[0] = v.point[0];
point[1] = v.point[1];
point[2] = v.point[2];
return *this; // enable chaining =

}
Digicube
Digicube
fair enough, does this apply for *=, -=, +=, type of operators?
fallenang3l
fallenang3l
quote:
Original post by Digicube
fair enough, does this apply for *=, -=, +=, type of operators?


Yeah, but you don''t have to check for self-assignment.
terminate
terminate
This is what I use for overloading += etc


  
const void CVECTOR3::operator += (const CVECTOR3& vec)
{
x += vec.x;
y += vec.y;
z += vec.z;
}


Those who dance are considered insane by those who cannot hear the music.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.