Unary Operator Overloading in C++

Unary Operator Overloading

Operator overloading allows us to use operators with objects and provide our own unique implementation of how operators interact with objects.

  • Overloading ++ / — operator to increment/decrement multiple member variables at once
  • Overloading + operator to concatenate two strings.

Syntax:

return_type:: operator unary_operator_symbol(parameters)
{
// function definition
}

Example

void operator ++() // operater overloading function
{
    a = ++a;
    b = ++b;
}

Addition/subtraction of Complex numbers using operator overloading

Let us look at an example below –

#include<bits/stdc++.h>
using namespace std;

class Complex 
{
    int a, b, c;
    public:
  
    Complex(int a1, int b1){ // paramterized constructor
        a = a1;
        b = b1;
    }

    void operator ++(){ //operater overloading function
        a = ++a;
        b = ++b;
    }
  
    void operator --(){ //operater overloading function
        a = --a;
        b = --b;
    }
  
    void display(){
        cout << a << " + " << b << "i" << endl;
    }
};

int main()
{
    Complex obj(20,15);

    ++obj;
  
    cout << "Increment Complex Number\n";
    obj.display();
  
    --obj;
  
    cout << "\nDecrement Complex Number\n";
    obj.display();
    
    return 0;
}

Output

Increment Complex Number
21 + 16i

Decrement Complex Number
20 + 15i