Unary Operators Overloading
# C++ Unary Operator Overloading
[ C++ Overloading Operators and Functions](#)
Unary operators operate on a single operand. Here are examples of unary operators:
* Unary minus operator, i.e., negation (-)
* Logical NOT operator (!)
Unary operators typically appear to the left of the object they operate on, such as !obj, -obj, and ++obj, but sometimes they can also be used as postfix, such as obj++ or obj--.
The following example demonstrates how to overload the unary minus operator (-).
## Example
#includeusing 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 unary minus (-) operatorDistance operator- (){feet = -feet; inches = -inches; return Distance(feet, inches); }}; int main(){Distance D1(11, 10), D2(-5, 11); -D1; // Apply negation D1.displayDistance(); // Display D1 -D2; // Apply negation D2.displayDistance(); // Display D2 return 0; }
When the above code is compiled and executed, it produces the following result:
F: -
YouTip