C++: Comparing Operators with Functions

By Stephen R. Davis

The intrinsic data types are built into the C++ language, such as int, float, and double and the various pointer types. C++ enables the programmer to define the operators for classes that the programmer has created in addition to these intrinsic operators. This is called operator overloading.

Normally, operator overloading is optional and not attempted by beginning C++ programmers. A lot of experienced C++ programmers don’t think operator overloading is such a great idea either. However, you will have to learn how to overload one operator: the assignment operator.

An operator is nothing more than a built-in function with a peculiar syntax. The following addition operation

a + b

could be understood as though it were written

operator+(a, b)

In fact, C++ gives each operator a function-style name. The functional name of an operator is the operator symbol preceded by the keyword operator and followed by the appropriate argument types. For example, the + operator that adds an int to an int generating an int is called int operator+(int, int).

Any existing operator can be defined for a user-defined class. Thus, I could create a Complex operator*(const Complex&, const Complex&) that would allow me to multiply two objects of type Complex. The new operator may have the same semantics as the operator it overloads, but it doesn’t have to. The following rules apply when overloading operators:

  • The programmer cannot overload the . (dot), :: (colon), .*, *->, sizeof and ?: (ternary) operators.

  • The programmer cannot invent a new operator. For example, you cannot invent the operation x $ y.

  • The syntax of an operator cannot be changed. Thus, you cannot define an operation %i because % is already defined as a binary operator.

  • The operator precedence cannot change. A program cannot force operator+ to be evaluated before operator*.

  • The operators cannot be redefined when applied to intrinsic types — you can’t change the meaning of 1 + 2. Existing operators can be overloaded only for newly defined types.

Overloading operators is one of those things that seems like a much better idea than it really is. Usually, operator overloading introduces more problems than it solves.