Users Online
· Guests Online: 46
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
Pre-increment and Post-increment Program in C++
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.
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
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.