operator overloading
Definition: operator overloading is a process in which a single operator is used to perform different task known as operator overloading. These operator overloading is again classified into two types:
1. Unary operator overloading
2. Binary operator overloading
A. Unary operator overloading:
In unary operator overloading a single variable is used to perform different tasks by operators like ++ & -- etc.. The Syntax for these unary operator overloading is
return_type operator symbol ()
for example let us consider a program as
#include<iostream>
using namespace std;
class op_overloading
{
private:
int i;
public:
op_overloading()
{
i=2;
}
void operator++()
{
i++;
}
void operator--()
{
i--;
}
void output()
{
cout<<"The value of i is:"<<i<<endl;
}
};
int main() {
op_overloading opo;
opo++;
opo.output();
opo--;
opo.output;
}
Here the op_overloading is a constructor as in object oriented programming language this is one of the main important topic.
And here in the above program ++ and -- operator is used to perform different tasks using single variable named "i". hence this is the way how a unary operator is overloaded. Now let us see how a binary operator is overloaded.
B. Binary Operator overloading:
As like Unary operator Binary operator also overloaded. In unary operator overloading only one variable is used and overloaded. But here in this Binary operator overloading we use two or more variables for performing the task.
The syntax for these Binary operator overloading is:
return_type operator symbol ( class name explicit_object name)
Here the operators are overloaded by passing one object reference to other object and these binary objects are used to mix or concatenate two strings, and they are used to mainly check the equality of two names, numbers or any decimal or floating pointing value as there we can use "==" operator for checking the equality.
Now let us consider a program for these binary operator overloading :
This example is completely based on the comparison operator overloading.
#include<iostream>
using namespace std;
class name
{
private:
int b;
public :
void _input()
{
cin>>b;
}
void operator==(name n3)
{
if(b==n3.a)
{
cout<<"Objects are equal"<<endl;
}
else
{
cout<<"Objects are not Equal"<<endl;
}
}
};
int main()
{
name n1,n3;
cout<<"\n Enter the n1 value"<<endl;
n1.input();
cout<<"\n Enter the n3 value"<<endl;
n3.input();
n1==n3;
return 0;
}
0 Comments