I was going through some book and I decided to write my own implementation of post-increment operator for user defined type. Here is the code.
#include <iostream>
using namespace std;
class X
{
int a;
public:
X(int x=1):a(x){}
X operator++(int)
{
X oldobj = *this;
(*this).a++;
return oldobj;
}
int get(){return a;}
};
int main()
{
X obj,obj2;
obj++ = obj2;
cout<< obj.get() << endl;
return 0;
}
I would expect the output to be 1 since obj2’s value will be copied after the increment is done. But the output was 2.
Thoughts?
P.S. I know this code will not win any medals and its fallacies. It is just for my understanding. Incidentally, ++obj = obj2 returns 1;
Is the behavior undefined?
As your syntax tells you, the postfix operator returns a copy of the old value, so that’s what gets incremented, not your object.
Basically,
Will do this:
You’re assigning
obj2to a temporary variable.