Overloading Operators

 < Day Day Up > 



An overloaded operator is a function taking the form operatorX() where X is the operator being overloaded. For instance, operator=() is the function name of the assignment operator.

Overloaded operator function parameter lists vary in number and type based on three criteria: 1) where the function is declared, 2) on what types it is intended to operate, and 3) what operator is being overloaded. For example, an overloaded assignment operator declaration appearing in a Foo class declaration might take the following form:

Foo& operator=(Foo& rhs) 

In this example the assignment operator is overloaded to operate on Foo objects taking a Foo object as an argument to the function. Assuming there are two Foo objects named f1 and f2, the overloaded assignment operator can be called on F1 in the following fashion:

f1 = f2;

The f1 object appears on the left side of the assignment operator and the f2 object appears on the right hand side. Here is an alternative way to call the overloaded operator:

f1.operator=(f2);

Calling the overloaded operator by its function name is referred to as an explicit call. The function call is made via the left hand side object, f1, taking the f2 object as an argument.

The overloaded assignment operator is an example of an operator that must be declared as a non-static class member function. However, some operators can be declared globally, meaning they do not belong to any particular class. An overloaded operator of this type will usually take two arguments.

The following sections discuss the implementation of different groups of operators in more detail.



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net