Overloading unary operators

Unary operators produce a result from a single operand. You can define overloads of a standard set of unary operators to work on user-defined types.

Overloadable unary operators

You can overload the following unary operators on user-defined types:

Unary operator overload declarations

You can declare overloaded unary operators either as non-static member functions or as nonmember functions. Overloaded unary member functions take no argument because they implicitly operate on this. Nonmember functions are declared with one argument. When both forms are declared, the compiler follows the rules for overload resolution to determine which function to use, if any.

The following rules apply to all prefix unary operators. To declare a unary operator function as a non-static member function, use this declaration form:

return-type operator op ();

In this form, return-type is the return type and op is one of the operators listed in the preceding table.

To declare a unary operator function as a nonmember function, use this declaration form:

return-type operator op ( class-type );

In this form, return-type is the return type, op is one of the operators listed in the preceding table, and class-type is the class type of the argument on which to operate.

The postfix forms of ++ and -- take an extra int argument to distinguish them from the prefix forms. For more information about the prefix and postfix forms of ++ and --, see Increment and decrement operator overloading.

Note

There's no restriction on the return types of the unary operators. For example, it makes sense for logical NOT (!) to return a bool value, but this behavior isn't enforced.

See also

Operator overloading