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++
#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++
#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 Overloading, Function Overloading, Operator Overloading in C#,C++ Interview Questions, Loading with Inheritance, Function Overloading and Function Overriding, Template in C++, etc.
Keep Grinding! Happy Coding!