Operator Overloading


  • Operator overloading allows the programmer to define how operators should interact with various data types.
  • At least one of the operands in any overloaded operator must be a user-defined type.
  • You can only overload the operators that exist.
  • All operators keep their current precedence and associativity, regardless of what they're used for.

General Rules

  • if the function is operator» or operator« for stream I/O,
  • or if it needs type conversions on its leftmost argument,
  • or if it can be implemented using the class's public interface alone,
    • make it a nonmember (and friend if needed in the first two cases)
      • if it needs to behave virtually
          • add a virtual member function to provide the virtual behavior, and implement it in terms of that
  • else make it a member
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.