Chebz
Chebz

Reputation: 1395

Operator overloading strange results

heres my class

class Vector
{
public:
    Vector();
    Vector(float x, float y, float z);

    float x;
    float y;
    float z;

    Vector &operator+(const Vector &other) const;
    Vector &operator+=(const Vector &other);
    Vector &operator*(float n) const;
};

//op overloading functions impl
Vector &Vector::operator+(const Vector &other) const
{
    Vector result = *this;
    result.x += other.x;
    result.y += other.y;
    result.z += other.z;
    return result;
}

Vector &Vector::operator+=(const Vector &other) 
{
    this->x += other.x;
    this->y += other.y;
    this->z += other.z;
    return *this;
}

Vector &Vector::operator*(float n) const
{
    Vector result = *this;
    result.x *= n;
    result.y *= n;
    result.z *= n;
    return result;
}

I am getting incorrect result when trying to use more complex equation. For example this WORKS:

Vector vChange = velocity * time;
position += vChange;

while this DOESNT:

position += velocity * time;

i.e. it compiles and runs but writes some bogus into position

Same for this one:

Vector& Reflect(const Vector& I, const Vector& N)
{
Vector v = I - 2 * Dot(N, I) * N;
}

Could you advise me what am I doing wrong? Thanks!

Upvotes: 0

Views: 121

Answers (3)

C. K. Young
C. K. Young

Reputation: 223003

For your operator* and operator+, you have to return the Vector by value, not by reference. What you have there is returning a dangling reference, and that is undefined behaviour.

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You're returning a reference to a local variable. Don't do that. Your non-assigning operators should return by value, not by reference.

Upvotes: 1

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234394

You are returning a reference to a local variable in operator*. That's undefined behavior. Return by value instead:

Vector Vector::operator*(float n) const
{
    Vector result = *this;
    result.x *= n;
    result.y *= n;
    result.z *= n;
    return result;
}

Same for operator+.

Upvotes: 5

Related Questions