C++ program to demonstrate unary operator overloading

This program demonstrate unary minus overloading in c. The value of x is read as input in the function getdata() and the putdata() function is used to display the value of x. The function void operator -() performs the overloading, which changes the sign of x to negative. In the main function, the statement a.getdata(); calls the function getdata() and the statement a.putdata(); calls the function putdata(). The statement -a; calls the function void operator -(), which overloads the unary minus operator. The statement a.putdata(); after the statement cout<<"\nAfter Overloading value of x="; prints the negative value of x.

Program

//program to overload unary operator -

#include<iostream.h>

#include<conio.h>

class overld

{

int x;

public:

void getdata()

{

cout<<"Enter the value for x";

cin>>x;

}

void putdata()

{

cout<<x;

}

void operator -()

{

x=-x;

}

};

void main()

{

overld a;

a.getdata();

cout<<"\nBefore Overloading value of x=";

a.putdata();

-a;

cout<<"\nAfter Overloading value of x=";

a.putdata();

getch();

}

No comments: