operator

C++ Specific —>

typeoperatoroperator-symbol**(parameter-list)**

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.

Rules of Operator Overloading

  • You can overload the following operators:

    + - * / % ^
    ! = < > += –=
    ^= &= |= << >> <<=
    <= >= && || ++ ––
    ( ) [ ] new delete & |
    ~ *= /= %= >>= ==
    != , –> –>*
  • If an operator can be used as either a unary or a binary operator, you can overload each use separately.

  • You can overload an operator using either a nonstatic member function or a global function that's a friend of a class. A global function must have at least one parameter that is of class type or a reference to class type.

  • If a unary operator is overloaded using a member function, it takes no arguments. If it is overloaded using a global function, it takes one argument.

  • If a binary operator is overloaded using a member function, it takes one argument. If it is overloaded using a global function, it takes two arguments.

Restrictions on Operator Overloading

  • You cannot define new operators, such as **.

  • You cannot change the precedence or grouping of an operator, nor can you change the numbers of operands it accepts.

  • You cannot redefine the meaning of an operator when applied to built-in data types.

  • Overloaded operators cannot take default arguments.

  • You cannot overload any preprocessor symbol, nor can you overload the following operators:

    . .* :: ?:
  • The assignment operator has some additional restrictions. It can be overloaded only as a nonstatic member function, not as a friend function. It is the only operator that cannot be inherited; a derived class cannot use a base class's assignment operator.

For more information, see C/C++ Operators and Operator Precedence Table.

END C++ Specific

Example

The following example overloads the + operator to add two complex numbers and returns the result.

// Example of the operator keyword
class Complex
{
public:
   Complex( float re, float im );
   Complex operator+( Complex &other );
   friend Complex operator+( int first, Complex &second );
private:
   float real, imag;
};

// Operator overloaded using a member function
Complex Complex::operator+( Complex &other )
{
return Complex( real + other.real, imag + other.imag );
};

// Operator overloaded using a friend function
Complex operator+( int first, Complex &second )
{
return Complex( first + second.real, second.imag );
}