C++ Unary Operator Overloading
C++ Overloading Operators and Functions
Unary operators operate on a single operand, and here are examples of unary operators:
Unary minus operator, i.e., the negative sign (-)
Logical NOT operator (!)
Unary operators usually appear on the left side of the object they operate on, such as !obj, -obj, and ++obj, but sometimes they can also be postfix, like obj++ or obj--.
The following example demonstrates how to overload the unary minus operator (-).
Example
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinity
int inches; // 0 to 12
public:
// Required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// Method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// Overload negative operator (-)
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1; // Negate
D1.displayDistance(); // Display D1
-D2; // Negate
D2.displayDistance(); // Display D2
return 0;
}
When the above code is compiled and executed, it produces the following result:
F: -11 I:-10
F: 5 I:-11
I hope the above example helps you better understand the concept of unary operator overloading. Similarly, you can try overloading the logical NOT operator (!).