I have success fully overloaded unary ++,--
postfix/prefix operator and my code works fine, but when ever in use (++obj)++
statement it returns unexpected result
here is code
class ABC
{
public:
ABC(int k)
{
i = k;
}
ABC operator++(int )
{
return ABC(i++);
}
ABC operator++()
{
return ABC(++i);
}
int getInt()
{
return i;
}
private:
int i;
};
int main()
{
ABC obj(5);
cout<< obj.getInt() <<endl; //this will print 5
obj++;
cout<< obj.getInt() <<endl; //this will print 6 - success
++obj;
cout<< obj.getInt() <<endl; //this will print 7 - success
cout<< (++obj)++.getInt() <<endl; //this will print 8 - success
cout<< obj.getInt() <<endl; //this will print 8 - fail (should print 9)
return 1;
}
have any solution or reason???
I find it best to implement post-increment in terms of pre-increment.
ABC operator++(int )
{
ABC result(*this);
++*this; // thus post-increment has identical side effects to post-increment
return result; // but return value from *before* increment
}
ABC& operator++()
{
++i; // Or whatever pre-increment should do in your class
return *this;
}