Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Unary Operator in C++ with examples?
3.
What is Unary Operator Overloading in C++ with examples ?
3.1.
Unary minus(-) Operator using Member Function
3.2.
Implementation :
3.3.
C++
3.4.
Overloading minus(-) Operator using Friend Function
3.5.
Implementation :
3.6.
C++
4.
Frequently Asked Questions
4.1.
How unary operators are overloaded?
4.2.
Where is unary operators used?
4.3.
What is unary vs binary operators in C++?
4.4.
What are some common mistakes to avoid when overloading unary operators in C++?
5.
Conclusion 
Last Updated: Mar 27, 2024
Easy

What is Unary Operator Overloading in C++?

Author Harshita Vyas
0 upvote

Introduction

In C++, unary operator overloading involves operators like +, -, !, &, *, ++, --, which operate on a single operand. The specific symbol used depends on the operation being overloaded (e.g., - for negation, ++ for increment).

unary operator overloading in c++

In this article, we shall explore the concept of unary operator overloading in C++ and discuss how it can be used to write more to-the-point codes. We will also look at the syntax and some examples to illustrate this feature of C++.

What is Unary Operator in C++ with examples?

A unary operator is an operator that operates on a single operand. These operators are used to perform operations on a single operand, such as changing the sign of a number or incrementing/decrementing its value. The most common unary operators in C++ are the unary plus (+) and unary minus (-) operators. The following are some examples of unary operators in C++, including:

  1. Unary plus (+): This operator is used to indicate a positive value. For example, if x = 9, then +x will also be 9.
    Syntax: + operand;
  2. Unary minus (-): This operator is used to indicate a negative value. For example, if x = 9, then -x will be -9.
    Syntax: - operand;
     
  3. Increment (++): This operator is used to increase the value of the operand by one. For example, if x = 9, then ++x will be 10.
    Syntax: ++operand;      //pre-increment  
                  operand++;      //post-increment
     
  4. Decrement (--): This operator is used to decrease the value of the operand by one. For example, if x = 9, then --x will be 8.
    Syntax:  -- operand;      //pre-decrement
                   operand--;       //post-decrement
     
  5. Logical NOT (!): This operator is used to get the opposite value of a boolean expression. For example, if x = true, then !x will be false.
    Syntax: !operand;


Note: It's important to note that increment and decrement operators (++ and --) are different among other unary operators in a way that they modify the value of their operand permanently. Other unary operators, such as the unary plus (+) and unary minus (-), do not change the value of their operand. So, when using increment and decrement operators, one must remember that the value of the operand will be permanently modified.

What is Unary Operator Overloading in C++ with examples ?

We know that operator overloading is a compile-time polymorphism, using which we can provide extra special meaning to an already existing operator. Unary operator overloading in object-oriented programming enables us to modify the behavior of unary operators. 

For example, We can use the unary minus(-) operator to operate only on predefined data types. But if we want to use it on class objects, we need to modify its preexisting behavior, this can be done through ‘unary operator overloading’. In ‘unary operator overloading’, we are just giving an additional meaning to an existing operator rather than changing its original meaning.

No arguments are passed in the unary operator function. It is used for overloading an operator that is operating on a single operand.

Syntax:

class className {
   ...
   public:
      returnType operator<symbol>() 
      {
         // custom behaviour for the operator
      }
   ...
};

 

In this syntax, 'className' is the name of the class for which the operator is being overloaded, 'returnType' is the data type that the operator returns, and '<symbol>' is the symbol of the unary operator being overloaded (e.g., +, -, !, ~, etc.).

The overloaded operator is defined inside the class, just like any other member function. The operator function takes no parameters since the operator operates on a single operand. The custom behavior of the operator is defined inside the function body.

The following are some examples of Unary Operator Overloading in C++:

Unary minus(-) Operator using Member Function

The unary minus operator is used to represent negative numbers. For example, if a variable x has the value 7, then -x would have the value -7. A unary operator does not take any argument as it works only on a single operand.

Implementation :

  • C++

C++

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

class Coordinates
{
public:
int X, Y; //The fields of the class

// Constructor to initialize the X and Y
Coordinates(int x, int y)
{
this->X= x;
this->Y = y;
}

// Overloading(-) operator for decrementing X and Y Coordinates

void operator-()
{
X--;
Y--;
cout << "\nDecremented X & Y are " <<
X << " and " << Y<<endl;
}

};

// Driver Code
int main()
{
Coordinates C(11,13);

// Using(-) unary operator for C

-C;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Decremented X & Y are 10 and 12

 

Here, we are overloading the minus(-) operator. This operator works on the object of the â€˜Coordinates’ class and decrements the â€˜X’ and â€˜Y’ coordinates.

Overloading minus(-) Operator using Friend Function

When you overload an operator using a friend function, you can access the private data members of the class, which would not be possible if you overload the operator using a member function, as the subclass cannot access the private members of the superclass.

To overload the minus (-) operator using a friend function, you need to declare the friend function inside the particular class and then define it outside the class. By defining a friend function to overload the minus (-) operator, you can create new and more intuitive syntax for operations involving objects of your class. This can make your code more readable and easier to understand.

Implementation :

  • C++

C++

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

class Coordinate
{
private:

int X;
int Y;//The fields

public:

//Constructor to initialize the value of X and Y
Coordinate(int x, int y) {
X = x;
Y = y;
}

// Overloading the minus operator (-) as a friend function
friend Coordinate operator-(const Coordinate &C);

//Function to display the coordinate
void display() {
cout << "X: " << X << ", Y: " << Y << endl;
}

};

//Defining the overloaded operator
Coordinate operator-(const Coordinate &C){
return Coordinate(-C.X, -C.Y);
}

int main(){
//Making object of Coordinate Class
Coordinate C1(20, 10);

//Defining coordinate C2 as negative of C1
Coordinate C2 = -C1;

//displaying C2
C2.display();
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

X: -20, Y: -10

 

Here, a friend function is defined for the â€˜Coordinate’ class. This friend function overloads the minus (-) operator for the â€˜Coordinate’ class. The overloaded minus operator is defined outside of the class definition. It takes a constant reference to a â€˜Coordinate’ object as its argument and returns a new â€˜Coordinate’ object with the â€˜X’ and â€˜Y’ fields negated. In the main() function, a â€˜Coordinate’ object â€˜C1’ is created with the values (20, 10). A new â€˜Coordinate’ object called â€˜C2’ is created and initialized to the negation of â€˜C1’ using the overloaded minus operator.

Frequently Asked Questions

How unary operators are overloaded?

To overload a unary operator in C++, you define a member function with the return type of your requirement. Then comes the "operator" keyword, followed by the sign of the operator. The function takes no arguments and returns a value. 

Where is unary operators used?

Unary operators are used for performing operations on a single variable or operand, for example, unary plus (+), unary minus(-), decrement(--), and increment(++).

What is unary vs binary operators in C++?

Unary operators in C++ operate on a single operand, usually altering or evaluating it in some way (examples include increasing x, decreasing y, and negating a condition). Conversely, pair operators work with two operands and perform operations between them (for example, adding a and b, multiplying x and y, or comparing c to d). Pair operators in expressions have two inputs, whereas unary operators only have one.

What are some common mistakes to avoid when overloading unary operators in C++?

Some common mistakes to avoid when overloading unary operators in C++ include forgetting to define the operator as a member function, forgetting to return a value from the operator function and defining the operator in a way that makes less sense to the original function of the operator.

Conclusion 

We hope you have gained enough knowledge about unary operator overloading in c++. In conclusion, unary operator overloading in C++ is a powerful feature that allows programmers to customise the behaviour of unary operators to work with user-defined data types. This feature can simplify code and make it more readable by allowing the use of natural and obvious syntax.

You can see our related articles like Operator OverloadingFunction OverloadingOperator Overloading in C#,C++ Interview Questions, Loading with InheritanceFunction Overloading and Function Overriding, Template in C++, etc.

Keep Grinding! Happy Coding! 

 

Live masterclass