Write a C++ program for implementing the unary operator overloading.

The unary operators operate on a single operand and following are the examples of Unary operators:
• The increment (++) and decrement (--) operators.
• The unary minus (-) operator.
• The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--.




Algorithm:
1. Start the process.
2. Invoke the class counter.
3. Crate two objects c1 and c2 and assign values to them.
4. Call c1.get_count() and then Call c2.get_count()
5. Increment the values C1++ , C2++ and ++c2
6. Print c1 and c2.
7. Stop the process

Program Code:
#include<iostream.h>
#include<conio.h>
class counter
{
int count;
public:
counter()
{
count=0;
}
int get_count()
{
return count;
}
void operator++()
{
count++;
}
};
void main()
{
counter c1,c2;
cout<<"\nC1 ="<<c1.get_count();
cout<<"\nC2 ="<<c2.get_count();
c1++; //Using overloaded ++ operator.
c2++;
++c2;
cout<<"\nC1 ="<<c1.get_count();
cout<<"\nC2 ="<<c2.get_count();
getch();
}




Output:
C1 = 0
C2 = 0
C1 = 1
C2 = 2
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: