Operator
overloading is
just “syntactic sugar,”
which means it is simply another way for you to make a function call.
The
difference is the arguments for this function don’t appear inside
parentheses, but instead surrounding or next to characters you’ve always
thought of as immutable operators.
There
are two differences between the use of an operator and an ordinary function
call. The syntax is different; an operator is often “called” by
placing it between or sometimes after the arguments. The second difference is
that the compiler determines what “function” to call. For instance,
if you are using the operator
+
with floating-point arguments, the compiler “calls” the function to
perform floating-point addition (this “call” is typically the act
of inserting in-line code, or a floating-point coprocessor instruction). If you
use operator
+
with a floating-point number and an integer, the compiler “calls” a
special function to turn the
int
into a
float,
and then “calls” the floating-point addition code.
But
in C++, it’s possible to define new operators that work with classes.
This definition is just like an ordinary function definition except the name of
the function begins with the keyword
operatorand
ends with the operator itself. That’s the only difference, and it becomes
a function like
any other function, which the compiler calls when it sees the appropriate
pattern.