Skip to content

Operator Overloading in c++

Reading Time: < 1 minute

C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading in c++ .

An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).

When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

Operator Overloading in C++ overloads all the operators in various ways.

Example: 

#include iostream.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<>h;
cout<>m;
cout<>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();
}

The above example overrides the + operator,to add to Time(hh:mm:ss) objects.

Note:

  1. Left operands types will be of ostream& and istream&
  2. Function overloading this operands must be a non member function because it is not a object of class.
  3. It must be a friend function to access private data members.
See also  PHP Calendar Coding - Annual Calendar Project
Tags:

Leave a Reply