Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ simple operator overloading for both directions

So I am trying to overload the operator* so both ways will work:

Myclass * a;
a * Myclass;

When I declare this function everything goes well:

Polynomial operator*(const double d);

But when I try doing it the other direction like this:

Polynomial operator*(Polynomial &, const double d)

I'm getting an error: "too many parameters for this operator function.

What am I doing wrong?

Thanks!

like image 959
Gil Avatar asked Feb 09 '23 09:02

Gil


1 Answers

When you overload a binary operator as a member function, the class instance is always the left-hand operator and the argument to the function is the right hand, there's nothing you can do to change it. Not if you want to continue using member only functions.

But if you use a global non-member function you can easily have whichever order you want. For example

class Polynomial { ... };

// Function that allows poly * 12.34
Polynomial operator*(const Polynomial& lhs, const double rhs)
{
    ...
}

// Function which allows 12.34 * poly
Polynomial operator*(const double lhs, const Polynomial& rhs)
{
    ...
}

And if you don't want to reimplement the same code in both functions, and the operator is commutative (like multiplication and addition should be) then you can implement one of the function by calling the other:

Polynomial operator*(const Polynomial& lhs, const double rhs)
{
    ...
}

Polynomial operator*(const double lhs, const Polynomial& rhs)
{
    return rhs * lhs;  // Calls the operator function above
}

Of course, the operator taking the Polynomial object as left-hand side may of course be implemented as a member function.


On a related note, if you have implemented the operator as a member function, e.g.

class Polynomial
{
    ...

    Polynomial operator*(const double rhs)
    {
        ...
    }
};

The the following code

Polynomial poly1(...);
Polynomial poly2 = poly * 12.34;

is equal to

Polynomial poly1(...);
Polynomial poly2 = poly.operator*(12.34);
like image 96
Some programmer dude Avatar answered Feb 16 '23 02:02

Some programmer dude