Image

C++ - Operator Overloading - Operator Overloading

Operator Overloading

Assigning additional task to an operator is called operator overloading. It is one of the feature of compile time polymorphism. Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type.

C++ support two types of operator

1. Unary Operator
2. Binary Operator
	Syntax:
	class <class_name>
	{
	public: return_type operator sign(arguments)
		{
		}
	}

Note : .,::,sizeof(),&,: can not be inherited

1. Unary Operator

A operator which apply on single operand is called as unary operator.

e.g: ++, --
WAP to overload ++ and --
#include<conio.h>
#include<iostream.h>
#include<math.h>
class Number{
  int a,b,c;
  public:
	Number(int i,int j,int k){
	  a=i;
	  b=j;
	  c=k;
	}
	void show(){
	   cout<<"\n a = "<<a;
	   cout<<"\n b = "<<b;
	   cout<<"\n c = "<<c;
	}
	void operator ++();
	void operator --();
};
void Number::operator ++(){
 a=abs(a);
 b=abs(b);
 c=abs(c);
}
void Number::operator --(){
 a=-abs(a);
 b=-abs(b);
 c=-abs(c);
}
void main()
{
 Number n(-5,6,-7);
 clrscr();
 cout<<"\nInitial values ";
 n.show();
 cout<<"\nAfter applying ++ operator ";
 n++;
 n.show();
 cout<<"\nAfter applying -- operator ";
 n--;
 n.show();
 getch();
}
O/P
Initial value
A=-5
B=6
C=-7
After applying ++ operator
A=-5
B=6
C=-7
After applying – operator
A=-5
B=6
C=-7
2. Binary Operator

A operator which apply on two or more than two operands is called as Binary operator.

e.g: +,-,*,/
WAP to overload + and – operator
#include<iostream.h>
#include<conio.h>
class Complex{
  int real,img;
  public:
	 void get()
	 {
	  cout<<"\n Enter real and img value ";
	  cin>>real>>img;
	 }
	 void show()
	 {
	  cout<<"\n"<<real<<" + "<<img<<"i";
	 }
	 Complex operator +(Complex c2){
	 Complex temp;
	 temp.real=real+c2.real;
	 temp.img=img+c2.img;
	 return temp;
	}
	 Complex operator -(Complex c1){
	 Complex temp;
	 temp.real=real-c1.real;
	 temp.img=img-c1.img;
	 return temp;
	}
};
void main(){
Complex c1,c2,c3;
clrscr();
cout<<"\n First equation : ";
c1.get();
cout<<"\n Second equation : ";
c2.get();
c3=c1+c2;
c1.show();
c2.show();
cout<<"\n for Add   :";
c3.show();
cout<<"\n for Sub   :";
c3=c1-c2;
c3.show();
getch();
}
O/P
Enter quation :
First  real and img value
5
6
Second real and img value
7
6
5+6
6+7
For Add
12+12i
For Sub
-2+0i