11.2. Fundamentals of Operator Overloading
C++ programming is a type-sensitive and type-focused process. Programmers can use fundamental types and can define new types. The fundamental types can be used with C++'s rich collection of operators. Operators provide programmers with a concise notation for expressing manipulations of objects of fundamental types.
Programmers can use operators with user-defined types as well. Although C++ does not allow new operators to be created, it does allow most existing operators to be overloaded so that, when these operators are used with objects, the operators have meaning appropriate to those objects. This is a powerful capability.
Software Engineering Observation 11.1
Good Programming Practice 11.1
Good Programming Practice 11.2
An operator is overloaded by writing a non-static member function definition or global function definition as you normally would, except that the function name now becomes the keyword operator followed by the symbol for the operator being overloaded. For example, the function name operator+ would be used to overload the addition operator (+). When operators are overloaded as member functions, they must be non-static, because they must be called on an object of the class and operate on that object.
To use an operator on class objects, that operator must be overloadedwith three exceptions. The assignment operator (=) may be used with every class to perform memberwise assignment of the data members of the classeach data member is assigned from the "source" object to the "target" object of the assignment. We will soon see that such default memberwise assignment is dangerous for classes with pointer members; we will explicitly overload the assignment operator for such classes. The address (&) and comma (,) operators may also be used with objects of any class without overloading. The address operator returns the address of the object in memory. The comma operator evaluates the expression to its left then the expression to its right. Both of these operators can also be overloaded.
Overloading is especially appropriate for mathematical classes. These often require that a substantial set of operators be overloaded to ensure consistency with the way these mathematical classes are handled in the real world. For example, it would be unusual to overload only addition for a complex number class, because other arithmetic operators are also commonly used with complex numbers.
Operator overloading provides the same concise and familiar expressions for user-defined types that C++ provides with its rich collection of operators for fundamental types. Operator overloading is not automaticyou must write operator-overloading functions to perform the desired operations. Sometimes these functions are best made member functions; sometimes they are best as friend functions; occasionally they can be made global, non-friend functions. We discuss these issues throughout the chapter.