Overloading Operators

You can overload one of the standard C++ operators by redefining it to perform a particular operation when it is applied to an object of a particular class. Overloaded operators must have at least one argument that has class type. An overloaded operator is called an operator function and is declared with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but, like overloaded functions, they are distinguished by the number and types of operands used with the operator.

You can overload any of the following operators:

+     -     *     /     %     ^     &     |     ~
!     =     <     >     +=    -=    *=    /=    %=
^=    &=    |=    <<    >>    <<=   >>=   ==    !=
<=    >=    &&    ||    ++    --    ,     ->*   ->
()    []    new   delete

where () is the function call operator and [] is the subscript operator.

Consider the standard + (plus) operator. When this operator is used with operands of different standard types, the operators have slightly different meanings. For example, the addition of two integers is not implemented in the same way as the addition of two floating-point numbers. C++ allows you to define your own meanings for the standard C++ operators when they are applied to class types.

You can overload both the unary and binary forms of:

      +      -      *      &

When an overloaded operator is a member function, the first operand is matched against the class type of the overloaded operator. The second operand, if one exists, is matched against the argument in the overloaded operator call.

When an overloaded operator is a nonmember function, at least one operand must have class or enumeration type. The first operand is matched against the first argument in the overloaded operator call. The second operand, if one exists, is matched against the second argument in the overloaded operator call.

An overloaded operator must be either a member function, as shown in the following example:

class X
{
public:
      X operator!();
      X& operator =(X&);
      X operator+(X&);
};
X X::operator!() { /* ... */ }
X& X::operator=(X& x) { /* ... */ }
X X::operator+(X& x) { /* ... */ }

or take at least one argument of class, a reference to a class, an enumeration, or a reference to an enumeration, as shown below:

class Y;
{
//      .
};
class Z;
{
//      .
};
Y operator!(Y& y);
Z operator+(Z& z, int);

Usually, overloaded operators are invoked using the normal operator syntax. You can also call overloaded operators explicitly by qualifying the operator name.



Argument Matching in Overloaded Functions


Overloading Unary Operators
Overloading Binary Operators
Restrictions on Overloaded Operators
Special Overloaded Operators
Overloading Functions
Example of an Overloaded Operator