Monday

operator overloading in c++ with example


Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
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.



Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded. Operator that are not overloaded are follows
  • scope operator - ::
  • sizeof
  • member selector - .
  • member pointer selector - *
  • ternary operator - ?:



Operator Overloading Example:
#include< iostream.h>
#include< conio.h>
class time
{
int h,m,s;
public:
 time()
 {
  h=0, m=0; s=0;
 }
 void getTime();
 void show()
 {
  cout<< h<< ":"<< m<< ":"<< s;
 }
time operator+(time);   //overloading '+' operator
};
time time::operator+(time t1) //operator function
{
time t;
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
}
void time::getTime()
{
 cout<<"\n Enter the hour(0-11) ";
 cin>>h;
 cout<<"\n Enter the minute(0-59) ";
 cin>>m;
 cout<<"\n Enter the second(0-59) ";
 cin>>s;
}
void main()
{
clrscr();
time t1,t2,t3;
cout<<"\n Enter the first time ";
t1.getTime();
cout<<"\n Enter the second time ";
t2.getTime();
t3=t1+t2; //adding of two time object using '+' operator
cout<<"\n First time ";
t1.show();
cout<<"\n Second time ";
t2.show();
cout<<"\n Sum of times ";
t3.show();
getch();
}






0 comments:

Post a Comment