How do we teach a normal C++ Operator to act on a user-defined operand? The keyword operator is used to overload the ++ operator in this declarator:
void operator ++ ()
The return type (void in this case) comes first, followed by the keyword operator, followed by the operator itself (++), and finally the argument list enclosed in parentheses (which are empty here). This declarator syntax tells the compiler to call this member function whenever the ++ operator is encountered, provided the operand (the variable operated on by the ++) is of type Counter.
We saw in Chapter 5, “Functions,” that the only way the compiler can distinguish between overloaded functions is by looking at the data types and number of their arguments. In the same way, the only way it can distinguish between overloaded operators is by looking at the data type of their operands. If the operand is a basic type like an int, as in
++intvar;
then the compiler will use its built-in routine to increment an int. But if the operand is a Counter variable, then the compiler will know to use our user-written operator++() instead.
The operator Keyword
Tags:
operator