overloading unary operators

what is unary operator?


unary operator = need for single operand like(++,--,etc.)


we know that this operator changes the sign of an operand when applied to a basic data item.

we will see how to overload this operator so that it can be applied to an object in much the same way as is applied to an int or float variable.

The unary minus when applied to an object should change the sign of each of its data items.


  • take one example using member function.


EXAMPLE:

#include<iostream>
using namespace std;
class ABC
{
int a,b,c;                              //data member
public:
void getdata(int x,int y,int z);     
void operator -();                   //overload - operator and no argument
void display();
};
void ABC :: getdata(int x,int y,int z)
{
a=x;                         //initialize with a,b,c
b=y;
c=z;
}
void ABC :: operator -()
{
a=-a;
b=-b;
c=-c;
}
void ABC :: display()
{
cout<<"\n a is:"<<a;
cout<<"\n b is:"<<b;
cout<<"\n c is:"<<c;
}
int main()
{
ABC t;
t.getdata(10,-20,-30);
t.display();
-t; 
t.display();
return 0;                        //either -t or t-

}



output:



Note

The function operator -() takes no argument.Then,what does this operator function do?it changes the sign of data members of the object t.Since this function is a member function of the same class,it can directly access the member of the object which activated it.

Remember,a statement like

t2=-t1;
will not work because,the operator-() does not return value.it can work if the function is modified to return an object.

it is possible to overload a unary minus operator using a friend function as follows:


Note

Note that the argument is passed by reference.it will not work if we pass argument by value because only a copy of the object that activated the call is passed to operator-().Therefore,the changes made insides the operator function will not reflect in the called object.

0 comments:

Copyright © 2013 free coding