Why post increment is always implemented in terms of pre increment.

Hi ppl :),

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 ?

Thanks for the help :)
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.
Thanks a lot @keskiverto for the well explained response.
2) Is there any guideline to implement post increment in terms of pre increment ?

There are general guidelines summarized at https://en.cppreference.com/w/cpp/language/operators (including a paragraph on increment/decrement)

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)
1
2
    _Tp operator++(int) noexcept {return fetch_add(_Tp(1));}
    _Tp operator++() noexcept {return fetch_add(_Tp(1)) + _Tp(1);}
Last edited on
Topic archived. No new replies allowed.