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.
/*
* C++ Program to overload pre-increment and post-increment operator
*/
#include <iostream>
using namespace std;
class Integer {
private:
int value;
public:
Integer(int v) : value(v) { }
Integer operator++();
Integer operator++(int);
int getValue() {
return value;
}
};
// Pre-increment Operator
Integer Integer::operator++()
{
value++;
return *this;
}
// Post-increment Operator
Integer Integer::operator++(int)
{
const Integer old(*this);
++(*this);
return old;
}
int main()
{
Integer i(10);
cout << "Post Increment Operator" << endl;
cout << "Integer++ : " << (i++).getValue() << endl;
cout << "Pre Increment Operator" << endl;
cout << "++Integer : " << (++i).getValue() << endl;
}
$ a.out Post Increment Operator Integer++ : 10 Pre Increment Operator Integer++ : 12