Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 978
fishfood Avatar asked Jul 28 '12 21:07

fishfood


People also ask

What is operator overloading * Your answer?

Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.

What is the order of operations in C++?

Math in C++ is very simple. Keep in mind that C++ mathematical operations follow a particular order much the same as high school math. For example, multiplication and division take precedence over addition and subtraction. The order in which these operations are evaluated can be changed using parentheses.

Can the precedence of an overloaded operator be changed can the number of operand be altered?

Overloading an operator cannot change its precedence.

Which operators can be overloaded?

The two member access operators, operator->() and operator->*() can be overloaded. The most common use of overloading these operators is with defining expression template classes, which is not a common programming technique.


1 Answers

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.

like image 198
Luchian Grigore Avatar answered Oct 26 '22 20:10

Luchian Grigore