operator++(int) and --(int) for my class INT

Hi, wanted to ask if this is a correct way to implement post increment and decrement.
This class is supposed to work like build in int.
1
2
3
4
5
6
7
8
9
10
11
12
class INT {
	int i;
public:
	INT(int ii) : i{ ii } {}
	operator int() { return i; }

	INT& operator++() { ++i; return *this; }
	INT operator++(int) { int temp = i; ++i; return temp; }   //is this the way to go?

	INT& operator--() { --i; return *this; }
	INT operator--(int) { int temp = i; --i; return temp; }   //is this the way to go?
};


If this is correct is this is why people usually tell that in for loops I should probably use pre increment to avoid temporary variable?
Last edited on
Hi, wanted to ask if this is a correct way to implement post increment and decrement.

Yes, it looks correct.

If this is correct is this why people usually tell that in for loops I should probably use pre increment to avoid temporary variable?

Yes. For simple types like int it probably makes no difference because it is easy for the compiler to optimize, but as a general rule it's good to prefer pre-increment because it could be faster than post-increment in some cases.
Last edited on
Tnx you man! :)
Topic archived. No new replies allowed.