next up previous
Next: About this document ... Up: Simple Classes: mycomplex0.h Previous: Functions acting on classes

Overloading operators

Clearly, it would be much more convenient to get the sum of two complex numbers by means of an arithmetic expression, as in

   complex a, b, sum;
   sum = a + b;
The compiler won't know how to interpret such an expression unless we tell it. C++ provides for overloading the + operator this way:

complex operator+(const complex &z1, const complex &z2)
{
  return complex(z1.re + z2.re, z1.im + z2.im);
}

In effect we are allowed to define a special purpose function named operator+ that adds its two arguments, just as cadd did. That is to say, when we write the expression a + b, the compiler interprets it as the special function call operator+(a,b), where the plus sign is the last character in the name of the function.

The + operator in this context is called a binary arithmetic operator because it takes two values. In algebra there is also a unary + operator as in x = +b. That operator has the same name, but takes only one argument. The operators -, *, and / are also binary operators, and the operator - can also be unary as in x = -b. All of these operators can be similarly overloaded for complex arithmetic, allowing us to build a wide range of expressions involving complex numbers.

The other new feature here is the use of the attribute const, which signals to the compiler that the argument is unchanged by the function. That makes sense here, because both terms being added are strictly input, so they are never changed. Always declaring input values as constant is good coding practice, but not always required. Here it is necessary, if we ever want to build compound expressions like a + b + c, where the result of the first addition becomes input to the second. The result of the first addition is a temporary intermediate, which we don't see. Feeding it to a function that might change it is not allowed, because it could result in a hard-to-detect bug. The compiler is reassured by const that it won't be changed.


next up previous
Next: About this document ... Up: Simple Classes: mycomplex0.h Previous: Functions acting on classes
Carleton DeTar 2017-02-13