C++ Program to Perform operator overloading on unary operator Increment ++ with no return type


January 21, 2023, Learn eTutorial
1057

In this C++ program, the increment ++ operator is overloaded. i.e., increase the value of a data member by 1 if the ++ operator operates on an object.

What is operator overloading?

Polymorphism: Polymorphism (or operator overloading) is a concept in object-oriented programming that allows one method or operator to be used differently for different operations. In C++, we can make one operator works differently on different objects or classes, or structures which is called operator overloading.
 

Operator overloading in C++

Create a class check and declare a variable i in private. The class members declared as private can be accessed only by the member functions inside the class. A constructor check () is created in public and set the value of variable i to 0. Here, we are using the operator ++ to work in a way that increases the value of the variable by 1. Now we make a function to display the value of the variable.

Within the main function body, create an object obj for the class check. Display the initial value of the data memberfor object obj. Invoke the operator function void operator ++( ). Perform the operation ++obj; Display the value of the data member after the operation using obj.Display();

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Create a class check with a private variable i

Step 4: create a constructor check( ); set the value of i to 0

Step 5: Define the function for operator overloading 

Step 6: Define function display for displaying the data member.

Step 7: call the function main

Step 8: create an object obj for the class check

Step 9: Display the value of the data member by accessing the function with the object

Step 10: call the function for operator overloading

Step 11: Display the data member after the operation by calling the display function.

Step 12: Exit 

C++ Source Code

                                          #include <iostream>
using namespace std;

class Check
{
    private:
       int i;
    public:
       Check(): i(0) {  }
       void operator ++() 
          { ++i; }
       void Display() 
          { cout << "i=" << i << endl; }
};

int main()
{
    Check obj;

    // Displays the value of data member i for object obj
    obj.Display();

    // Invokes operator function void operator ++( )
    ++obj; 
  
    // Displays the value of data member i for object obj
    obj.Display();

    return 0;
}
                                      

OUTPUT

i=0
i=1