Overloading Unary Operator
Let us consider overloading (-) unary operator. In the unary operator function, no arguments should be passed. It works only with one class object. It is the overloading of an operator operating on a single operand.
Example: Assume that class Distance takes two member objects i.e. feet and inches, and creates a function by which the Distance object should decrement the value of feet and inches by 1 (having a single operand of Distance Type).
// C++ program to show unary
// operator overloading
#include <iostream>
using namespace std;
class Distance {
public:
int feet, inch;
// Constructor to initialize
// the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to
// perform decrement operation
// of Distance object
void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " <<
feet << "'" << inch;
}
};
// Driver Code
int main()
{
Distance d1(8, 9);
// Use (-) unary operator by
// single operand
-d1;
return 0;
}
Output
Feet & Inches(Decrement): 7'8
Explanation: In the above program, it shows that no argument is passed and no return_type value is returned, because the unary operator works on a single operand. (-) operator changes the functionality to its member function.
Note: d2 = -d1 will not work, because operator-() does not return any value.
Types of Operator Overloading in C++
C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change the function of some specific operators to do some different tasks.
Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function
Here,
- Return_Type is the value type to be returned to another object.
- operator op is the function where the operator is a keyword.
- op is the operator to be overloaded.
Operator Overloading can be done by using three approaches, i.e.
- Overloading Unary Operator.
- Overloading Binary Operator.