Unary operator overloading - C++ Program

Q. Write a C++ program to overload unary operators that is increment and decrement.

Answer:

Operator overloading is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. It is used to perform operation on user-defined data type.

Following program is overloading unary operators: increment (++) and decrement (--).

#include<iostream>
using namespace std;

class IncreDecre
{
        int a, b;
     public:
        void accept()
        {
                cout<<"\n Enter Two Numbers : \n";
                cout<<" ";
                cin>>a;
                cout<<" ";
                cin>>b;
        }
        void operator--() //Overload Unary Decrement
        {
                a--;
                b--;
        }
        void operator++() //Overload Unary Increment
        {
                a++;
                b++;
        }
        void display()
        {
                cout<<"\n A : "<<a;
                cout<<"\n B : "<<b;
        }
};
int main()
{
        IncreDecre id;
        id.accept();
        --id;
        cout<<"\n After Decrementing : ";
        id.display();
        ++id;
        ++id;
        cout<<"\n\n After Incrementing : ";
        id.display();
        return 0;
}


Output:

unary operator overloading