Operator Overloading
Operator Overloading
Definition
Note:
Although the semantics of an operators can be extended we can not
change its syntax & grammatical rules such as no of operator
precedence & associatively.
Syntax for Operator Overloading
<return type> operator <op> ( arguments )
{
//body of the function ;
}
Rules:
O/P:
1 0
Overloading of Increment & Decrement
Operators (Prefix)(++)
class A
void main()
{ int x ; {
A obj(2);
public: ++obj; // obj.operator ++ ;
A(int a) {x=a; } obj.display();
}
void display()
{cout<<x; }
void operator ++ ()
{
++x;
}
};
Overloading of Increment& Decrement
operators (Postfix)(++)
class A void main()
{
{ int x ;
A obj(5);
public: obj++; // obj.operator ++(int) ;
obj.show();
A(int a) {x=a; } }
void show()
{cout<<x; }
void operator ++ (int)
x++;
}
};
Overloading Operators using Friend
Functions
Using friend function we can not overload certain
operators. These are
Assignment operator ( = )
Function call operators ()
Subscripting operator [ ]
Class member access operator ->
Overloading Minus using Friend Function
class A
void main()
{ int x, y; {
public: A ob1;
void get(int a, int b) ob1.get(-11,-12);
ob1.disp();
{ x=a; y=b; }
-ob1; //operator -(ob1);
friend void operator -(A &); ob1.disp();
void disp() }
{ cout<<x<<" "<<y; }
};
void operator -(A &o1)
{
o1.x = -o1.x;
o1.y = -o1.y;
}
Overloading Arithmetic operator using
Friend Function
void main()
class A
{
{ int x, y;
A o1(10,20), o2(50,60),o3;
public:
o3=o1+o2; //o3=operator + (o1,o2);
A() { }
o3.show();
A(int a, int b)
}
{ x=a; y=b; }
void show()
{ cout<<x<<y; }
friend A operator +(A,A);
};
A operator +(A obj1 ,A obj2)
{
A temp;
temp.x=obj1.x+obj2.x;
temp.y=obj1.y+obj2.y;
return temp;
}
Rules for Operator Overloading