-
Overloading * Operator
I am trying to overload the * operator to multiply two objects of my class. Since it is a binary operator I know that the function should take a LHS and a RHS parameter. However, when I try the following, I get a compiler error saying :
`Polynomial Polynomial:: operator*(Polynomial, Polynomial)' must take either zero or one argument
Code:
class Polynomial
{
public:
Polynomial operator*(Polynomial a, Polynomial b);
When I give it only one parameter, then it compiles. But unless I am mistaken, then it will not be able to actually multiply two polynomials. Thanks in advance.
-
Make it a non-member friend function if you want to use two arbitrary Polynomial objects.
-
When you are using an operator within a class, the left-hand side is "this" - you can either make it a friend function outside the class, or only take one argument of "rhs".
--
Mats
-
Often if you have a operator* (or operator+, -, /, %) then you should also have operator*= (or operator+=, -=, /=, %=). Then, a good way to implement operator* would be to create a temporary copy of the left hand side object, then use operator*= on it with the right hand side object and return the result.
This has the benefit of keeping the code in one place for both operators, which reduces the chance of bugs and differing behavior. It also means that operator* doesn't need to be a friend. operator*= would be implemented as a member function.