The operators such as +, -, *, /, >, < etc is pre-defined in programming languages. They can perform the operations on built-in (standard) data types only. They do not work for user-defined data types such as objects.
C++ allows programmers to perform the operations on user-defined data
types called objects. This feature called operator overloading.
With operator overloading, a programmer is allowed to provide his own
definition for an operator to a class.
Like function overloading, operator overloading is also a form of compile
time polymorphism.
The operator overloading function is preceded by the keyword operator followed
by an operator.
Operator overloading function must be
defined in public section of the class.
Syntax:-
class class_name
{
public:
returntype operator op (args_list)
{
statements;
}
};
Here, op is the operator that has to be overloaded
The following operators can be used in operator overloading.
a) Unary operators - ++,
--, -, !
b) Binary operators –
arithmetic, relational, and logical operators
c) Other operators – [],
(), =>, ->, new and delete operators
The operators that cannot be overloaded
a) Scope resolution
operator (: :)
b) Member selection
operator (.)
c) Ternary operator (? : )
Implementing
Operator Overloading
Operator overloading is usually implemented in two ways.
1) Through member function
2) Through friend function
1) Through
Member Function
· Number
of explicit parameters is reduced by one, because calling object implicitly supplies
one operand.
·
Unary
operators take no explicit parameter.
·
Binary
operators take one explicit parameter.
·
Left-hand
operand has to be the calling object.
·
Obj2=obj1+10
is permissible, but obj2=10+obj1 is not permissible.
2) Through
Friend Function
·
Number of explicit
parameters is more.
·
Unary operators take
only one parameter.
·
Binary operators take
two parameters.
·
Left-hand operand need
not be an object.
·
Obj2=obj1+10 as well as
obj2=10+obj1 is permissible.
No comments:
Post a Comment