Show Lecture.IncrementDecrementMethods as a slide show.
If you’re writing a class that is numeric or pointery, then it needs:
++obj
)
obj++
)
--obj
)
obj--
)
None of these come for free. You have to write them all.
Preincrement is easy:
// Change the state of the object // Return the object by reference Whatever &operator++() { // No argument means preincrement // Do what is needed to change the object // which might be *this += 1; return *this; }
Whatever &
, a reference to the current object.
Postincrement is harder, but can be the same for nearly all classes:
// Save a copy of the object // Change the state of the object // Return the copy by value Whatever operator++(int) { // Dummy int arg means postincrement const auto save = *this; ++*this; // Call the preincrement method return save; }
Pre-/post-decrement is essentially the same. Get pre-/post-increment working, and then (I can’t believe that I’m saying this) use copy & paste.
operator++
should use operator+=
to accomplish
the increment. Less duplication of information—good!