Operator Overloading – Introduction
Operators like + (plus), – (minus), * (multiply), / (divide) work very well with data types such as int, float, etc. But when it comes to user defined data types these operators do not work on their own. To make them work, we need to define special functions that tell the operators how to handle the operands of the user defined class. These special functions are known as operator functions.
The general form of an operator function is: return_type classname :: operator op(arg) { ——— function body ——— }
Where the return_type specifies the value returned by the operator function and op is the operator being overloaded. The operator op should always be preceded by the keyword operator as shown in the syntax. arg denotes the argument passed to the operator function.
A+B
Here A is invoking the operator function while B is the argument passed to the operator function.
An operator function must either be defined as the member function of the class overloading the operator or as a friend function of that class. The basic difference between using a friend function and a member function is that in the case of a friend function all the objects using that operator need to be passed as arguments. Therefore, in the case of binary operators both the operands have to be passed as arguments to a friend function. This is not the case when using member functions as only one argument needs to be passed since the other operand is the one invoking the member function. Operator functions are declared in the class using prototypes as follows:
1. | vector operator+(vector); | //vector addition |
2. | vector operator-(); | //unary minus |
3. | friend vector operator+(vector, vector) | //vector addition |
4. | friend vector operator-(vector& ); | //unary minus |
5. | vector operator-(vector a); | //subtraction |
6. | int operator == (vector); | //comparison |
vector is a user defined data type. In the above examples, 1 and 3 do the same work, but 1 is a member function while 3 is a friend function. Note that the first takes one argument, but the second takes two arguments.
In this Series
- Introduction to operator overloading
- Overloading unary operators
- Overloading binary operators
Comments - No Responses to “Operator Overloading – Introduction”
Sorry but comments are closed at this time.