Coupon Accepted Successfully!


Overloading Unary Operators

Overloading devoid of explicit argument to an operator function is called unary operator overloading. The operators ++, −−, and − are unary operators. The unary operators ++ and −− can be used as prefix or suffix with the functions. These operators have only single operand. The following examples illustrate the overloading of unary operators.

10.3 Write a program to increment member variables of object. Overload unary ++ operator.


Explanation: In the above example the class num contains four integer variables a, b, c, and d. The class also has two-member functions show() and operator ++() and one parameterized constructor. The constructor is used to initialize object. The show() displays the contents of the member variables. The operator ++() overloads the unary operator ++. When this operator is used with integer or float variables, its value is increased by one. In this function, ++ operator precedes each member variable of class. This operation increments the value of each variable by one.

In function main(), the statement ++X calls the function operator ++(), where X is an object of the class num. The function can also be called using statement X. operator ++(). In the output, values of member variables before and after increment operations are displayed.

10.4 Write a program to overload – operator.

Explanation: The above program is same as previous one. Here, the operator – is overloaded. The statement –X calls the function operator –(). The function operator–() makes all the member variables negative. The function show() displays the values of member variables on the screen.

Test Your Skills Now!
Take a Quiz now
Reviewer Name