Overloading operators (C++ only)

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.

An overloaded operator is called an operator function. You declare an operator function 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.

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 any of the following operators:

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

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

You can overload both the unary and binary forms of the following operators:

+ - * &

You cannot overload the following operators:

. .* :: ?:

You cannot overload the preprocessor symbols # and ##.

An operator function can be either a nonstatic member function, or a nonmember function with at least one parameter that has class, reference to class, enumeration, or reference to enumeration type.

You cannot change the precedence, grouping, or the number of operands of an operator.

An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list.

You must declare the overloaded =, [], (), and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.

The operators new, delete, new[], and delete[] do not follow the general rules described in this section.

All operators except the = operator are inherited.



[ Top of Page | Previous Page | Next Page | Contents | Index ]