Unary Operator Overloading in C++


This C++ program demonstrates operator overloading using the class box, which has an integer data member x and two overloaded increment operators.

  • The box class has a default constructor that initializes the data member x to 0, and a parameterized constructor that sets the data member x to the provided value.
  • The box class overloads both the prefix ++ operator and the postfix ++ operator using two different member functions. The prefix ++ operator is overloaded using the member function operator++(), which increments the data member x by 1. The postfix ++ operator is overloaded using the member function operator++(int) , which also increments the data member x by 1 but returns the previous value of x.
  • In the main() function, the program creates an object o of the box class using the default constructor and prints its value. Then, it uses the prefix ++ operator to increment the value of o and print the new value. Next, it uses the postfix ++ operator to increment the value of o and print the new value.
  • When the program is executed, it prints the initial value of x, the value of x after the prefix ++ operator is applied, and the value of x after the postfix ++ operator is applied.

Source Code

/*
    Unary Operator Overloading in C++
*/
 
#include<iostream>
using namespace std;
class box
{
private:
    int x;
public:
    box()
    {
        x=0;
    }
    box(int a)
    {
        x=a;
    }
 
    void print()
    {
        cout<<"X : "<<x<<endl;
    }
 
    void operator ++()
    {
        ++x;
    }
    void operator ++(int)
    {
        x++;
    }
};
int main()
{
    box o;
    o.print();
    ++o;
    o.print();
    o++;
    o.print();
    return 0;
}
 
 

Output

X : 0
X : 1
X : 2
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples