-3

I have a vec2 class, defined like this

class vec2 {
public:
    float x, y;

    ...

    //add a scalar
    vec2 operator+(float s) const {
            return vec2(this->x + s, this->y + s);
        }
};

The operator+ overload works good when doing vec2 v = otherVector * 2.0f; but doesn't work when doing it backwards, like so vec2 v = 2.0f * otherVector;.

What's the solution to this?

McLovin
  • 3,295
  • 7
  • 32
  • 67

1 Answers1

0

Taking your example, the expression

otherVector * 2.0f

is equivalent to

otherVector.operator+(2.0f)

Creating an overloaded operator as a member function only allows the object to be on the left-hand side, and the right-hand side is passed to the function.

The simple solution is to add another operator overload, as a non-member function

vec2 operator+(float f, const vec2& v)
{
    return v + f;  // Use vec2::operator+
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621