Reliable Software Logo

C++ In Action: Language

Operator overloading

You can pretty much do any kind of arithmetic in C++ using the built-in integral and floating-point types. However, that's not always enough. Old-time engineers swear by Fortran, the language which has built-in type complex. In a lot of engineering applications, especially in electronics, you can't really do effective calculations without the use of complex numbers.

C++ does not support complex arithmetics. Neither does it support matrix or vector calculus. Does that mean that engineers and scientists should stick to Fortran? Not at all! Obviously in C++ you can define new classes of objects, so defining a complex number is a piece of cake. What about adding, subtracting, multiplying, etc.? You can define appropriate methods of class complex. What about notational convenience? In Fortran you can add two complex numbers simply by putting the plus sign between them. No problem! Enter operator overloading.

In an expression like

double delta = 5 * 5 - 4 * 3.2 * 0.1;
you see several arithmetic operators: the equal sign, the multiplication symbol and the minus sign. Their meaning is well understood by the compiler. It knows how to multiply or subtract integers or floating-point numbers. But if you want to teach the compiler to multiply or subtract objects of some user-defined class, you have to overload the appropriate operators. The syntax for operator overloading requires some getting used to, but the use of overloaded operators doesn't. You simply put a multiplication sign between two complex variables and the compiler finds your definition of complex multiplication and applies it. By the way, a complex type is conveniently defined for you in the standard library.

An equal sign is an operator too. Like most operators in C++, it can be overloaded. Its meaning, however, goes well beyond arithmetics. In fact, if you don't do anything special about it, you can assign an arbitrary object to another object of the same class by simply putting an equal sign between them. Yes, that's right, you can, for instance, do that:

SymbolTable symTab1 (100);
SymbolTable symTab2 (200);
symTab1 = symTab2;

Will the assignment in this case do the sensible thing? No, the assignment will most definitely be wrong, and it will result in a very nasty problem with memory management. So, even if you're not planning on overloading the standard arithmetic operators, you should still learn something about the assignment operator; including when and why you would want to overload it. And that brings us to a very important topic--value semantics.


NextNext: Passing by Value