Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between operator++ () and operator++ (int)? [duplicate]

Tags:

c++

operators

int

I have these code of lines from a program my teacher made :

 TimeKeeper& operator++() {
        d_seconds++;
        return *this;
  }
  const TimeKeeper operator++(int) {
        TimeKeeper tk(*this);
        ++(*this);
        return tk;
  }

And one of the questions my teacher asked us was "operator++() returns a reference and operator++ (int) returns a value, explain why?"

Can anyone explain this to me?? If you need the rest of the code i dont mind putting it on! Thanks!!

like image 752
user2843560 Avatar asked Dec 26 '22 16:12

user2843560


1 Answers

The one without an extra int is the preincrement operator while the one with the extra int parameter is the post increment operator. This somewhat awkward notation is somewhat of a hack to distinguish the two notations and the int can't be used for any useful purpose:

TimeKeeper keeper;
++keeper; // pre increment: calls TimeKeeper::operator++()
keeper++; // post increment: calls TimeKeeper::operator++(int)

The difference between pre increment and post increment is that for pre increment the value of the expression is that after the increment while for post increment it is the value before the expression. For post increment the object the increment is applied to gets moved forward and a different object representing the state before the increment is returned. The object representing the previous state is a temporary object which only lives within the expression and which, thus, needs to be returned by value. For the pre increment only one value is involved and that can be returned immediately by reference.

In the above snippet the result from keeper++ isn't used: you should only ever use the post increment operator when using its result. Otherwise it will just waste creating a temporary object pretty much along the lines of your teacher's code which is then thrown away. Even if the construction is cheap, it may waste a couple of CPU cycles. The same overloading and reasoning for not using it unless necessary applies to the decrement operator operator--(). Oddly enough, C++ is thus not idiomatic C++!

like image 101
Dietmar Kühl Avatar answered Apr 08 '23 17:04

Dietmar Kühl