Search This Blog
Saturday, September 18, 2010
The basics of operator overloading
Operator overloading resembles function overloading. In fact, operator overloading is really just a type of function overloading. However, some additional rules apply. For example, an operator is always overloaded relatively to a user defined type, such as a class. Other difference will be discussed as needed.
When an operator is overloaded, that operator loses none of its original meaning. Instead, it gains additional meaning relative to the class for which it is defined.
To overload an operator, you create an operator function. Most often an operator function is a member or a friend of the class for which it is defined. However, there is a slight difference between a member operator function and a friend operator function.
The general form of a member operator function is shown here:
return-type class-name::operator#(arg-list)
{
// operation to be performed
}
The return type of an operator function is often the class for which it is defined (however, operator function is free to return any type). The operator being overloaded is substituted for #. For example, if the operator + is being overloaded, the operator function name would be operator+. The contents of arg-list vary depending upon how the operator function is implemented and the type of operator being overloaded.
There are two important restrictions to remember when you are overloading an operator:
• The precedence of the operator cannot be change.
• The number of operands that an operator takes cannot be altered.
Most C++ operators can be overloaded. The following operators cannot be overload:
. :: .* ?
Also, you cannot overload the pre-processor operators (.* is highly specialised and is beyond the scope of this course).
Remember that C++ defines operators very broadly, including such things as the [ ] subscript operator, the ( ) function call operators, new and delete, and the dot and arrow operator. However, we will concentrate on overloading the most commonly used operators.
Except for the =, operator functions are inherited by any derived class. However, a derived class is free to overload any operator it chooses (including those overloaded by the base class) relative to itself.
Note, you have been using two overloaded operators: << and >>. These operators have been overloaded to perform console I/O. As mentioned, overloading these operators does not prevent them from performing their traditional jobs of left shift and right shift.
While it is permissible for you to have an operator function perform any activity, it is best to have an overloaded operator's actions stay within the spirit of the operator's traditional use.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment