C++ Language



Admission Enquiry Form

  

Operator overloading in C++
(Unary Operator overloading)




Operator overloading in C++

You have to recall the concept of function overloading which means one function is performing more than one jobs.

So here in operator overloading if one operator is peroforming more than one operation then we can say operator is overloaded.

So we can also think about C++ has given us the facility to create our own data type that is in the form of class. As we know user defined class is also known as user defined data type. So we can create our own data types in C++. Then we can also create our own operators also to work with our data types.But we are not allowed to create our new operators but we are allowed in C++ to assign new job to the existing operator to work with our own class.

We can create an operator() function in our class to overload operaters in C++




Unary Operator Overloading in C++:

Program of Unary Operator Overloading in C++

//Unary operator overloading
#include<iostream>
using namespace std;
class Demo
{
int x;

public:
Demo()//default constructor
{
x=0;
}
void setData(int n)
{
x=n;
}
int getData()
{
return x;
}
void operator++()//this is operator function
{
x=x+5;//will increment value of x by 5
cout<<endl<<"This is unary pre-increment operator";
}
void operator++(int)
{
x=x+5;
cout<<endl<<"This is unary post-increment operator";
}

};//end of class
int main()
{
Demo d;//creating object of Demo
d.setData(10);//calling function to set value
++d;//calling d.operator++()
cout<<endl<<"value of x="<<d.getData();
d++;//calling d.operator++(int)
cout<<endl<<"value of x="<<d.getData();

}//end of main


Output:

This is unary pre-increment operator
value of x=15
This is unary post-increment operator
value of x=20