fishfood
fishfood

Reputation: 4282

operand order in * operator overload

I'm writing a vec3 class for my game physics engine.

I've made an operator overload to allow me to multiply a vector by a scalar (to scale the vector):

const vec3 operator*( const real n ) const
{
    return vec3(
        m_x * n,
        m_y * n,
        m_z * n
    );
}

This works correctly, if I use the correct order in my calculation:

float rImpulse;
vec3 vContactNormal;
...
vec3 vImpulse = vContactNormal * rImpulse;

if I change the order of multiplication (e.g. if I put the scalar first in the calculation), then compiler doesn't like this and highlights it as an error.

Can I update my vec3 class, so that order of multiplication doesn't matter? How? (I'll probably slap my forehead when I see the answer!)

Update

I've removed my original operator overload from the vec3 class and placed the following two operator overloads outside the vec3 class:

const vec3 operator*( const vec3 & v, const real r )
{
    return vec3( 
        v.x() * r, 
        v.y() * r, 
        v.z() * r 
    );
}
const vec3 operator*( const real n, const vec3 & v )
{
    return v * n;
}

Upvotes: 7

Views: 3384

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

You need to declare a free operator, outside the class (or inside, as a friend):

const vec3 operator*( const real n, vec3 v )
{
    //no need to re-implement, since you already have v * n defined
    return v * n;
}

The reason is that, when declared as a class member, the first operator is implicitly this, so you basically have defined vec3 * real.

Upvotes: 11

Related Questions