Thread: Overloading * Operator

  1. #1
    Registered User
    Join Date
    Mar 2006

    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

    class Polynomial
     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.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Make it a non-member friend function if you want to use two arbitrary Polynomial objects.
    My best code is written with the delete key.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    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".

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Often if you have a operator* (or operator+, -, /, &#37 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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. Operator Overloading (Bug, or error in code?)
    By QuietWhistler in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2006, 08:38 AM
  4. C++ Operator Overloading help
    By Bartosz in forum C++ Programming
    Replies: 2
    Last Post: 08-17-2005, 12:55 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM