Unary operators overloading in C++

Unary operators overloading in C++

It’s operate on the object for which they were called and normally, this operator appears on a left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj–.
• The increment (++) and decrement (–) operators.
• The unary minus (-) operator.
• The logical not (!) operator.

Example 1

#include<iostream.h>

class Distance

{

private: int feet; // 0 to infinite

int inches; // 0 to 12 public:

// required constructors of class

Distance()

{

feet = 0;

inches = 0;

}

Distance(int f, int i)

{

feet = f;

inches = i;

} // method that display distance

void displayDistance()

{

cout << “F: ” << feet << ” I:” << inches <<endl;

}

// overloaded minus (-) operator as

Distance operator- ()

{

feet = -feet; inches = -inches;

return Distance(feet, inches);

}

};

int main()

{

Distance Di1(11, 10), Di2(-5, 11);

-Di1; // apply negation

Di1.displayDistance(); // displayDi1

-Di2; // apply negation

Di2.displayDistance(); // display

Di2

return 0; }

Output
F:-11 I:-10

F:5,I:-11

F:-11,I:-10

F:5,I:-11

Example 2

#include<iostream.h>

#include<conio.h>

class complex1

{

int aa,bb,cc;

public: complex1()

{}

void getvalue2()

{

cout<<“Enter the Two Numbers:”;

cin>>aa>>bb;

}

void operator++()

{

aa=++aa;

bb=++bb;

}

void operator–()

{

aa=–aa;

bb=–bb;

}

void display2()

{

cout<<aa<<“+\t”<<bb<<“i”<<endl;

}

};

void main()

{

clrscr();

complex1 obj;

obj.getvalue2();

obj++;

cout<<“Increment Complex Number\n”;

obj.display2();

obj–;

cout<<“Decrement Complex Number\n”;

obj.display2();

getch();

}

Output
Enter the Two Numbers:5

7

Increment Complex Number

6+        8i

Decrement Complex Number

5+       7i

Leave a Reply

Your email address will not be published. Required fields are marked *