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.
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.
/*
* 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
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]Related Posts:
- Practice Programming MCQs
- Check Programming Books
- Check C++ Books
- Apply for Computer Science Internship
- Check Computer Science Books