Overloaded unary operator
1 minute read
How many arguments are required in the definition of an overloaded unary operator?
Ø One argument is required in the definition of an overloaded unary operator, if it friend function then zero (0) argument.
Ø This is because the object used to invoke the member function is passed implicitly and therefore is available for the member function.
Ø In friend function arguments may be passed either by value of reference.
Ø Example:
op x or x op // for member function
Or
operator op(x) // for friend function
7. Explain overloading of unary operators with example?
Ø The unary operator can be overloaded.
Ø The unary operator takes only one operand.
Ø The following program shows how the unary minus operator is overloaded.
Ø Example:
#include <iostream.h>
class space
{
int x;
int y;
int z;
public:
void getdata(int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void display(void)
{
cout << x << “ “;
cout << y << “ “;
cout << z << “ \n”;
}
void operator-() //overload minus operator
{
x = -x;
y = -y;
z = -z;
}
};
int main()
{
space S;
S.getdata(10,-20,30);
cout << “S : “;
S.display();
-S; // activates operator-() function
cout << “S : “;
S.display();
return 0;
}
Ø The program produces the following output:
S : 10 -20 30
S : -10 20 -30
Ø Note : function operator-() takes no argument.