Operator Overloading: Dr.S.Veena, Associate Professor/CSE
Operator Overloading: Dr.S.Veena, Associate Professor/CSE
• Operator Overloading is performed by adding special member functions to the class, which is known as operator
functions. It is used to convert one object into another.
• Defining Operator Overloading
Operator overloading is done through a special function called operator function. The special form of an operator
function is
retrun-type class-name :: operator op(arg-list)
{
function body // task defined
}
Where return-type is the type of value returned by the specified operation and op is the operator being overloaded.
The op is preceded by the keyword operator. Operator op is the function name.
A friend function will have only one argument for unary operators and two for binary operators. Arguments
may be passed either by value or by reference.
A member function has no arguments for unary operators and only one for binary operators. This is because the
object used to invoke the member function is passed implicitly and therefore is available for the member
function.
• Operators should follow syntactical rules for the original meaning when overloaded. Following are some
examples of the same
1. All arithmetic operators must return a value. However, it can be of a different type than what is returned to by
original operator.
2. Unary operators, do not have any explicit arguments. If it overloaded as friend, they take one reference
argument.
3. Binary operators take one explicit argument as member and take two explicit arguments as friend.
Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.
There are some operators that cannot be overloaded.
We cannot use friend functions to overload certain operators. However, member functions can be used to
overload them.
Unary operators, overloaded by means of a member function, take no explicit arguments and return no
explicit values, but, those overloaded by means of a friend function, take one reference argument (the object
of the relevant class).
Binary operators overloaded through a member function take one explicit argument and those which are
overloaded through a friend function take 2 explicit arguments.
When using binary operators overloaded through a member function, the left hand operand must be an
object of the relevant class.
Binary arithmetic operators such as +, -, *, and / must explicitly return a value. They must not attempt to
change their own arguments.
Operators Meaning
Sizeof sizeof operator
. Membership operator
.* Point-to-Member
operator
:: Scope Resolution
Operator
?: Conditional operator
Operators Meaning
= Assignment operator
[] Subscripting operator