Operator Overloading - RHS object is modified by assignment operation
Dear cBoard,
I wrote a 3d vector class, and it works pretty well. I was hoping to overload some operators to make the class a bit easier to use.
Where * operator is over loaded to scale the vector by a scalar float.
Code:
Vec3f a, b;
//assign relevant values to a.x, a.y, and a.z
a.normalize();
b = a * CONST_FLOAT_0; //This modifies a
//b is used for something
b = a * CONST_FLOAT_1
I've never used operator overloading much. I read a couple pages about operator overloading and realized that I didn't understand references very well. I read the eternally confuzzled page about pointers and references. I won't lie it left me pretty confused, but gave me a better idea of what's going on.
The problem is very clear to me. It's doing what I expect it to, but not what I want it to.
Somehow, during an assignment operation nothing on the right side should be modified.
Here is = and *
Code:
Vec3f& Vec3f::operator=(const Vec3f& rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
return *this;
}
Vec3f& Vec3f::operator*(const float& rhs)
{
x *= rhs;
y *= rhs;
z *= rhs;
return *this;
}
I think I could fix it if I understood how data is flowing in these functions.
Why would an assignment operator return a value? when operator= is called, isn't it being called by the left hand side? So what is that return value doing, seems like this function should be void to me.
I guess using references allows you to have multiple assignments on one line, I'll have to figure that one out.
When I use
b = a * float;
how can the * operator know that it shouldn't change a?
I tried creating a temporary Vec3f in operator* and then modifying it and returning it, but that didn't fix the problem.
How should these overloaded operators work?
Thank You
EDIT:
Here's the class declaration:
Code:
class Vec3f {
public:
Vec3f();
Vec3f(float xi, float yi, float zi);
~Vec3f();
float x,y,z;
Vec3f operator+(Vec3f rhs);
Vec3f operator-(Vec3f rhs);
Vec3f& operator*(const float& rhs);
Vec3f operator/(float rhs);
Vec3f operator+=(Vec3f rhs);
Vec3f& operator=(const Vec3f& rhs);
float dot(Vec3f rhs);
Vec3f cross(Vec3f rhs);
float getMag();
float getXAngle();
float getYAngle();
void setAngle(float a);
void setAngles(float xa, float ya);
void normalize();
void print();
protected:
float xAngle_;
float yAngle_;
};