What are the basic rules for operator overloading in C++?

The following rules constrain how overloaded operators are implemented. However, they do not apply to the new and delete operators, which are covered separately.

  • You cannot define new operators, such as **.
  • You cannot redefine the meaning of operators when applied to built-in data types.
  • Overloaded operators must either be a nonstatic class member function or a global function.
  • Operators obey the precedence, grouping, and number of operands dictated by their typical use with built-in types.
  • Unary operators declared as member functions take no arguments; if declared as global functions, they take one argument.
  • Binary operators declared as member functions take one argument; if declared as global functions, they take two arguments.
  • If an operator can be used as either a unary or a binary operator ( & ,*, + , and - ), you can overload each use separately.
  • Overloaded operators cannot have default arguments.
  • All overloaded operators except assignment ( operator= ) are inherited by derived classes.
  • The first argument for member-function overloaded operators is always of the class type of the object for which the operator is invoked (the class in which the operator is declared, or a class derived from that class). No conversions are supplied for the first argument.