Operator Overloading in C++ Language (part 2)


Overloading of Unary Operator




Overload Unary Minus(-) Operator using class Member function. Unary operator acts on one operand only. In case overloaded operator function is a class member function, then it will act on the object with which it is called and use it as operand.

The unary operator operate on a single operand and following are the examples of Unary operator –
  • ·         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 sometime they can be used as postfix as well like obj ++ or obj --.

Following example explain how pre/post increment and decrement (--) operator can be overloaded:

 Pre increment :

operator overloading ,operator overloading in c++
unary operator overloading

OUTPUT


Post increment :



operator overloading ,operator overloading in c++
operator overloading


In the  quote given above, argument(int) we have passed, just to give the compiler the difference between pre and post increment operators i.e integer operator++() and integer operator++(int).

OUTPUT




Following example explain how minus (-) operator can be overloaded:


operator overloading ,operator overloading in c++

As we are looking at the quotation given above, the minus operator will be define in the same way as a plus operator, but when we don't call as + operator , we do not use two operands but use only single operand (caller object (c1) itself  used in unary operator's object) as we seen in above example i.e c2= -c1;(like we use in c language x=-3).


OUTPUT




If this article is helpful to you then please like and share.. thank you..


Comments

Popular posts from this blog

Notepad, Wordpad and Paint

HOW TO PASS CCC EXAM WITH ONE ATTEMPT (NIELIT)

Inheritance in C++ Language(part 1)