Pre-increment and Post-increment Program in C++
Posted by Superadmin on August 08 2022 09:42:53

Pre-increment and Post-increment Program in C++

 

 

This C++ program overloads the pre-increment and post-increment operators for user-defined objects. The pre-increment operator is an operation where the value attribute of the object is incremented and the reference to resulting object
returned whereas in the post-increment operator, a local copy of the object is saved, the value attribute of the object is incremented and the reference to the local copy of the object is returned.

 

Here is the source code of the C++ program which overloads the pre-increment and post-increment operators for user-defined objects. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to overload pre-increment and post-increment operator
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Integer {
  8.     private:
  9.         int value;
  10.     public:
  11.         Integer(int v) : value(v) { }
  12.         Integer operator++();
  13.         Integer operator++(int);
  14.         int getValue() { 
  15.             return value;
  16.         }
  17. };
  18.  
  19. // Pre-increment Operator
  20. Integer Integer::operator++()
  21. {
  22.     value++;
  23.     return *this; 
  24. }
  25.  
  26. // Post-increment Operator
  27. Integer Integer::operator++(int)
  28. {
  29.     const Integer old(*this);
  30.     ++(*this);
  31.     return old;
  32. }
  33.  
  34. int main()
  35. {
  36.     Integer i(10);
  37.  
  38.     cout << "Post Increment Operator" << endl;
  39.     cout << "Integer++ : " << (i++).getValue() << endl;
  40.     cout << "Pre Increment Operator" << endl;
  41.     cout << "++Integer : " << (++i).getValue() << endl;
  42. }

 

$ a.out
Post Increment Operator
Integer++ : 10
Pre Increment Operator
Integer++ : 12