This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, September 1, 2022

Overloading Unary operator

 Overloading Unary operator

In the following program the unary minus operator is used. A minus operator used as a unary, takes just one operand.

/* Program that Shows how the unary minus operator is overloaded. */
#include<iostream>
using namespace std;

class simple
{
    int x;
    int y;
    int z;

  public:
     void getdata(int a, int b, int c);
     void display(void);
     void operator-();   //overload unary minus
};

void space::getdata(int a, int b, int c)
{
    x=a; 
    y=b;
    z=c;
}

void space::display(void)
{
    cout<<"x="<<x<<" ";
    cout<<"y="<<y<<" ";
    cout<<"z="<<z<<" ";
}

void space::operator-()
{
    x=-x;
    y=-y;
    z=-z;
}

int main(){
    space S;
    S.getdata(120,-230,340);
    cout<<"S: ";
    S.display();
    -S;               //activates operator-() function
    cout<<"-S: ";
    S.display();
    return 0;
}

the output of the above given program would be:
S: x=120 y=-230 z=340
-S: x=-120 y-230 z=-340
Remember, a statement like 
S2=-S1;
will not work because the function operator-() does not return any 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:
 friend void operator-(space &s);     //declaration
 void operator-(space &s)                //definition
{
    s.x = -s.x;
    s.y = -s.y;
    s.z = -s.z;
}

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget