Operator Overloading
Operator Overloading
• C++ has the ability to provide the operators with the
special meaning for a data type.
• The mechanism of giving such special meanings to an
operator is known as Operator overloading.
• It provides a flexible option for creation of new
definitions for most of C++ operators.
• Operator Overloading is a specific case of
polymorphism in which some or all of operators like +,
=, or == have different implementations depending on
the types of their arguments.
• if a,b and c are variables(objects) of user defined data
type(class) then the statement c=a+b; will not work as
complier do not know how to add two variables(objects) of
user defined data type(class). Error will be generated.
• In order to make this operation possible we need to overload
the + operator by making a function to perform the desired
task.
• This property of giving additional meaning to the existing
operators so that they can work with variables of user
defined data type is called operator overloading.
• Providing additional meaning to an existing operator does not
change the original meaning of operator but it simply extends
the functionality of operator.
Operator Overloading
• Operator overloading refers giving special meaning to an
existing operator.
• In order to give additional meaning to the operator , we need
to overload it by creating an operator function
• An operator function defines the operation that the
overloaded operator will perform when used with the objects
of a relative class
• An operator function can be member or non member(friend
function) of a class
Syntax for operator function
• When declared inside and defined outside the class
return_type classname:: operator#(argument list)
{
Body of function
}
• When defined inside the class
return_type operator#(argument list)
{ body of function}
Contd….
• We can overload all C++ operators except the
following:
[Link] member access operator(.,.*).
[Link] resolution operators(::)
[Link] operator( sizeof)
[Link] operators(?:)
Restrictions on Operator Overloading
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
Operators that cannot be overloaded
. .* :: ?: sizeof
• The operator keyword is used to overload an
operator # which is one of the C++ operator to be
overloaded
• The complier distinguishes between ordinary
member function and operator function of a class
by checking the keyword operator.
• The name of the operator function is operator#
• In order to overload + operator we replace # by +.
• The no. of arguments to be passed to operator
function depends on whether the operator to be
overloaded is unary(++ or --) or binary(+,-,*)
• If the operator is unary then the argument list is
empty
• If the operator is binary the argument list will
contain one parameter.
• Examples of overloaded operator function:
void operator ++();
complex operator +(complex);
void operator +=(complex);
Steps in process of overloading
• Create a class that defines data types that is to be
used in the overloading operation.
• Declare the operator function operator op() in
public part of the class. It may be either member
function or a friend function.
• Define the operator function to implement the
required operation.
Types of Operator
• Unary operator
• Binary operator
Operator invocation
• Overloaded operator functions can be invoked (for
binary operator) as:
x op y
Can be interpreted as:
x . operator op (y) for member function
operator op (x , y) for friend function
Types of Operators
• Unary operator
• Binary operator
Operators Member Functions Non Member
Functions (Friend
Function)
Unary operator No Parameter One Parameter
Prefix 0 1
postfix 1(int) 2 (class object, int)
Binary operator One Parameter Two Parameters
Unary Operators
• The unary operators operate on a single operand (-
a, +a, --a, a--, ++a, a++)
Overloading Unary Operator
• Are defined by either a member function that takes no
parameter or a non-member function that takes one
parameter
Example:
[Link] -()
or
operator -(i1)
or
-i1
Create a class item, having three data members x ,y and z,
overload ‘-’ (unary operator) to change the sign of x, y and z
class abc void display() int main()
{ {
private: {
cout<<x; abc s(10,-20,30);
int x;
cout<<y; cout<<"s :";
int y;
cout<<z<<"\n"; [Link]();
int z;
} -s;
public:
void operator-() cout<<"s :";
abc (int a, int b, int c)
{ [Link]();
{
x=a; x=-x; getch();
y=b; y=-y; return (0);
z=c; z=-z; }
} }
};
• It is possible to overload a unary minus operator using
friend function
friend void operator- (space &s); //declaration
void operator- (space &s) //definition
{
s.x = -s.x;
s.y = -s.y;
s.z= -s.z;
}
unary – operator that negates the object of
point class
#include <iostream.h>
class point
// Operator – operator for point class
{
point point::operator-( )
int x, y;
{
public:
x=-x;
point()
y=-y;
{
}
x = 0; y = 0;
int main()
}
{
point(int i , int j)
point o1(10 , 10);
{
-o1; //Negate the object
x=i; y=j;
[Link]();
}
}
point operator –( );
void display()
{
Cout<<x<<“\t”<<y;
}
};
Example of overloading Unary operator
#include<iostream.h> int main()
{
#include<conio.h>
//clrscr();
using namespace std;
score s1,s2; // object definition
class score
cout<<"\n initial value of s1 object = "<<[Link]();
{
cout<<"\n initial value of s2 object = "<<[Link]();
private: int val;
++s1; //operator function call
public: score()
++s1; // same as [Link]++();
{ val=0;} ++s2;
void operator++() //operator cout<<"\n final value of s1 object = "<<[Link]();
function definition
cout<<"\n final value of s2 object = "<<[Link]();
{ val= val+1; }
getch();
int show()
return 0;
{ return (val); }
}
};
Binary Operators
• Binary operator works on two operands
• (a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a<b, a<=b,
a==b)
Program to overload + (addition) operator.
Addition of complex numbers
class complex int main()
{ int x, y; { complex
public:
C1(2,3),C2(4,5),C3;
complex()
{ x=10; y=20;} C3=C1+C2;
Complex(int a,int b){x=a;y=b} [Link]();
complex operator +(complex c) }
{
complex temp;
temp.x= x+ c.x;
temp.y=y+c.y;
return(temp);
} C3=c1+c2
void show()
{ cout<<x<<“+i”<<y; } C3=[Link]+(c2);
};
Overloading binary operator using friends
• Declaration-
Friend complex operator+(complex, complex);
• Definition-
Complex operator+(complex e1, complex e2)
– { complex temp;
temp.x = e1.x + e2.x;
temp.y = e2.y + e2.y;
return (temp);
–}
Calling
E3= operator+(e1,e2);
Rules for overloading operators.
• Only existing operators can be overloaded. New
operators cannot be created.
• The overloaded operator must have at least one
operand that is of user defined type.
• We cannot change the basic meaning of the
operator.
• Overloaded operators follow the syntax rules of the
original operators. They cannot be overridden.
Rules for overloading operators.
• There are some operators that cannot be
overloaded.
• We cannot use friend functions to overload certain
operators. Member functions can be used to
overload them.
• Unary operators overloaded by means of member
function, take no explicit arguments and return no
explicit values.
Rules for overloading operators.
• Binary operators overloaded through a member
function take one explicit argument.
• When using binary operators overloaded through a
member function, the left hand operand must be
an object of the relevant class.
• Which are the operators that cannot be overloaded in
C++?(neither by member functions or global/friend
function)
1. sizeof operator
2. class member access operator(., .*)
[Link] operator(:?)
[Link] Resolution operator (::)
• Which are the operators that cannot be overloaded
by global/friend function(means operator that can be
over loaded as member functions only)
1. assignment operator(=)
[Link] member access operator(->)
[Link] operator []
[Link] call operator ()