
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Overload Unary Minus Operator in C++
Unary operators are operators that operate only on a single operand (unlike binary operators, which operate on two operands). There are mainly thirteen unary operators that exist in C++, for example, ++, !, ~, typeof, delete, etc.
Overloading Unary Minus Operator
Overloading a unary operator means defining a custom behavior for the unary operators while applying it to objects of a class. which means you can define how an operator will work when applied to instances of a class instead of using its default behavior. This operator is normally used on the left side of the object, as in +obj, !obj, -obj, and ++obj, but sometimes it can be used as a postfix as well, like obj++ or obj--.
So, overloading the unary minus operator defines the customized behavior of the minus operator. As its default behavior is used to negate values, meaning changing from positive to negative, but when it is overloaded for a custom class, then you can specify and customize its behavior according to the needs of your class.
Syntax
Here is the following syntax for overloading the unary minus operator in C++.
class ClassName { public: // Overload the unary - operator ClassName operator-() { // Define the custom behaviour here } };
ClassName is he name of your class.
The operator-() function is used for overloading the unary minus operator.
Example of Overloading Unary Minus Operator
#include <iostream> using namespace std; class Point { private: int x, y; public: // Constructor initializing x and y coordinates Point(int a, int b) : x(a), y(b) {} // Method to display the point's coordinates void display() const { cout << "(" << x << ", " << y << ")" << endl; } // Overloading the unary - operator Point operator-() { return Point(-x, -y); // Negate both x and y } }; int main() { Point p1(3, 4); Point p2 = -p1; cout << "Original Point: "; p1.display(); cout << "Negated Point: "; p2.display(); return 0; }
Output
Original Point: (3, 4) Negated Point: (-3, -4)
Explanation
- Firstly, the class point is created with two private members, x and y, and a constructor that initialises a Point object with values passed to it.
- Point operator-() overloads the unary - operator, which returns a new point object with both x and y negated.
- p2 = -p1 calls the overloaded - operator, creating a new point (-3, -4) and storing it in p2.