Unary Operator Overloading in C++

Unary Operator overloading

  • Operator overloading is a compile polymorphic technique where a single operator can perform multiple  functionalities
  • As a result, the operator that is overloaded is capable to provide special meaning to the user-defined data types as well.

Here we can overload unary operators like + +,–, unary + and  unary – to directly manipulate the object of a class

Syntax:

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

Here operator is a keyword and unary operator symbol is the operator to be overloaded

Read more on Operator Overloading in C++ here

Unary Operator overloading

Steps to perform unary operator overloading

  • Declare the class with its variables and its Member function
  • Using the function get_data()to read two numbers
  • Define the function operator ++ to add the values
  • Define the function of the operator — to subtract values
  • Define the display function
  • Define the class object  &call the function get_data()
  • Call the function operator ++() by incrementing in the class object and call the function display()
  • Call the function  operator –() by the decrementing  in the class object and call the function display()

C++ program to perform addition and subtraction can complex numbers using operator overloading

class complex 
{
int a, b, c;
public:

complex()
{
}

void get_data()
{
cout << "Enter the Two Numbers:";
cin >> a>>b;
}

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

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

void display()
{
cout << a << "+\t" << b << "i" << endl;
}
};

main()
{
complex c;
c.get_data();
c++;
cout << "Increment Complex Number\n";
c.display();
c--;
cout << "Decrement Complex Number\n";
c.display();

}

Output

Enter the two numbers: 3 5 
Increment Complex Number
4 + 6i
Decrement Complex Number
2 + 4i

Please Login/Signup to comment