Unary Operator Overloading in C++It is polymorphism when we overload an operator to carry out the same operation on objects of the same class. Simple unary operators cannot be used with class objects since they do not comprehend the behavior of member variables and will result in compilation errors. We use operator overloading for user-defined data type (object of a class) operations to give operators a user-defined meaning. We may use unary operator overloading in C++ by defining a new operator function in the class itself or by using the global friend function made for the operator function. What is a Unary Operator in C++?C++ comes with a large range of operators that can be used to perform mathematical and logical operations on numerical numbers. One such widely used operator is the unary operator. Unary Operators are employed in operations with a single operand. Unlike binary operators, unary operators do not need two operands to calculate the result. The unary operator is used to determine the new value of a single operand or variable. When using unary operators, the operand can be in either the prefix or postfix position. Unary operators have equal precedence, right-to-left associativity, and a variety of forms. Syntax:The following is the syntax for C++'s unary operator overloading: Here are a few examples of unary operators:
Let's use an example to clarify unary operator overloading in C++. I). Unary Operator Overloading for User-Defined Classes:Output: Original complex number: 3 + 4i Negated complex number: -3 + -4i II. Overloading the class Member function for the unary minus (-) operatorLet's take an example to understand how to define the class Member function for the unary minus (-) operator in C++: Output: num1: Value: 7 num2 (after unary minus): Value: -7 III. Overloading the global friend function's unary minus (-) operatorLet's take an example to understand how to define the global friend function's unary minus (-) operator in C++: Output: c1 = -5 - i4 c2 = 5 + i4 Explanation:
Conclusion:
Next TopicUnique_ptr in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India