I was checking on overloading pre and post increment operators for a class and I could see almost in every example, post increment is implemented in terms of pre increment.
I have following questions about this :
1) Why is it advised to implement post increment in terms of pre increment. I came
across a post mentioning not using pre increment to implement post increment
can cause buggy behavior. If this is true, Kindly let me know how, if this is
true.
2) Is there any guideline to implement post increment in terms of pre increment ?
Post-increment is trivial to implement with pre-increment. It should be quite difficult to make an error there.
Lets assume that you implement pre and post separately. Each computes the increment. You will have two copies of the same computation in your codebase.
Lets further assume that the computation is not trivial. A large block of code.
Did you write both independently (and possibly make mistake in one)?
Did you create one by copy-paste from the other?
Your class evolves. The increment has to be updated. How do you want to apply the edits to both copies? What if you forget one of them?
You make the maintenance unnecessarily difficult, if you have more than one copy.
in practice, like with every engineering decision, it's not universal.
For example , std::atomic<int> usually implements both increments in terms of the common underlying operation. quoting from LLVM libc++ (gnu libstdc++ similar, but longer)