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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.