Why do u do that ?

hey guys,
So, in the code below there's this piece of code that could be written in a way simpler way and still give the same result, but I've seen this probably unnecessary ( maybe not ) complexity applied in a couple of projects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>     // std::cout
#include <iterator>     // std::iterator, std::input_iterator_tag

class MyIterator : public std::iterator<std::input_iterator_tag, int>
{
  int* p;
public:
  MyIterator(int* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) {return p!=rhs.p;}
  int& operator*() {return *p;}
};

int main () {
  int numbers[]={10,20,30,40,50};
  MyIterator from(numbers);
  MyIterator until(numbers+5);
  for (MyIterator it=from; it!=until; it++)
    std::cout << *it << ' ';
  std::cout << '\n';

  return 0;
}


I'm talking about this part:
1
2
MyIterator& operator++() {++p;return *this;}
MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}


I experimented with the following code and got the same result:
1
2
MyIterator& operator++() {++p;return *this;}
MyIterator operator++(int) {operator++();}


I also did it this way and it worked exactly the same :
 
MyIterator& operator++(int) {++p;return *this;}


Could someone explain why the first (original) method is preferred ?

And there's something else that i don't get, why do we need to use an int argument for the ++ operator overload function ?

Any answers would be appreciated.
MyIterator operator++(int) {operator++();}

this shouldn't even compile you need to return a value
C++ has both pre-increment and post increment operators.

With pre-increment (++p), the value is incremented before the value is used.

With post-increment (p++), the value is incremented after the value is used.

The code for pre-increment is obvious. Increment the value, then return the updated value.

The code for post-increment is more subtle. Since the value of the operator function has to return the value BEFORE the value is incremented, the value is stored in a temporary variable. The real variable is incremented, then the temporary which contains the value before the increment is returned.

The int is simply a flag to the compiler to distinguish pre-increment (no flag) from post-increment operator functions. It serves no other purpose.

You got the same result in both cases because your program was not properly testing pre-increment and post-increment values.
Thanks, i got it ;)
Topic archived. No new replies allowed.