Program Showing The Overloading Of Prefix And Postfix Increment Operators In 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


The statement s2 = ++s1; on execution invokes the prefix operator ++ ( ) function that first increments the data member val of object s1 by 1 and then assign to s2 object (using temp object).

The statement s2 = s1++; on execution invokes the postfix operator ++ (int) function that first assign the s1 object to s2 object (using temp object) and then increment the data member val of object s1 by 1.

OUTPUT

Initial value of s1 object =  0

Initial value of s2 object =  0

s1 =   1

s2 after prefix operation =   1

s1  =  2

s2 after postfix operation =  1