Program To Overload Unary Increment Operator (++) Using C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


In this program we overload the operator ++ to increment the data member val of an object of the class score by 1.In the statement

++s1;

s1 is an object of class score and not a variable of built in data type.Hence in order to make this statement work, we need to overload the unary operator ++ by defining the operator function in the class score with function header as

void operator ++ ( )

In this function header ,the keyword operator is preceded by the return type void and is followed by the ++ i.e. the operator to be overloaded.This function header informs the compiler to invoke the overloaded operator function ++  whenever an object of class score is pefixedwith the unary increment operator ++. So when the compiler encounters the statement ++s1; it generates the call s1.operator ++ ( ) and hence control is transferred to operator function operator ++ ( ).

The operator ++ ( ) takes no parameters because being the member function of class score it must be called in association with an object of class score. The ++ is a unary operator that involves only one operand.So in the statement  ++s1; where the operand s1 is the object itself through which we are calling the operator function operator ++ ( ) and hence there is no need to pass any argument.

OUTPUT

Initial value of s1 object =  0

Initial value of s2 object =  0

Final value of s1 object   =   2

Final value of s2 object  =   1