Unary Operator Overloading in C++

Unary Operator Overloading

Unary Operator overloading in C++ allows us to use operators with objects and provide our own unique implementation of how operators interact with objects.
Unary Operator Overloading in C++

Unary Operator Overloading in C++

  • Overloading ++ / — operator is used to increment/decrement multiple member variables at once
  • Overloading + operator is used 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 –

Run
#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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription