Friday, February 5, 2010

C++ - What is overloading unary operator?

What is overloading unary operator?  

Unary operators are those which operate on a single variable. Overloading unary operator means extending the operator’s original functionality to operate upon object of the class. The declaration of a overloaded unary operator function precedes the word operator.
For example, consider class 3D which has data members x, y and z and overloaded increment operators:
class 3D 
{
         int x, y, z; 
         public: 
              3D (int a=0, int b=0, int c=0)
              {
                     x = a; 
                     y = b;
                     z = c; 
              }
              3D operator ++() //unary operator ++ overloaded 
               {
                        x = x + 1;
                        y = y + 1; 
                        z = z + 1; 
                        return *this; //this pointer which points to the caller object
               }
               3D operator ++(int) //use of dummy argument for post increment 
                          operator
               { 
                      3D t = *this; 
                       x = x + 1;
                       y = y + 1; 
                       z = z + 1;
                      return t; //return the original object
               }
               3D show() 
                {
                       cout<<”The elements are:\n”
                       cout<<”x:”<x<<”, y:y <<”, z:”<z;
                }
};
int main()
{
        3D pt1(2,4,5), pt2(7,1,3);
         cout<<”Point one’s dimensions before increment are:”<< pt1.show();
         ++pt1; //The overloaded operator function ++() will return object’s this pointer 
         cout<<”Point one’s dimensions after increment are:”<< pt1.show();
         cout<<”Point two’s dimensions before increment are:”<< pt2.show();
          pt2++; //The overloaded operator function ++() will return object’s this pointer 
          cout<<”Point two’s dimensions after increment are:”<< pt2.show();
           return 0;
}
The o/p would be:
Point one’s dimensions before increment are: 
x:2, y:4, z:5
Point one’s dimensions after increment are: 
x:3, y:5, z:6
Point two’s dimensions before increment are: 
x:7, y:1, z:3
Point two’s dimensions after increment are: 
x:7, y:1, z:3
Please note in case of post increment, the operator function increments the value; but returns the original value since it is post increment.

0 Comments: