What is overloading unary operator? - C++

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:”<<this→x<<”, y:<<this→y <<”, z:”<<this→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 output 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.
Difference between overloaded functions and overridden functions
Difference between overloaded functions and overridden functions - Overloading is a static or compile-time binding and Overriding is dynamic or run-time binding....
What is function overloading and operator overloading?
What is function overloading and operator overloading? - Function overloading: A feature in C++ that enables several functions of the same name can be defined with different types of parameters or different number of parameters...
Use of this pointer
Explain the use of this pointer - The this keyword is used to represent an object that invokes the member function...
Post your comment