1

In C++11 I am having issue implementing const iterator int my class code (inside .cpp file) I have:

class MyClass{ public: class iterator; iterator begin() const; iterator end() const; class const_iterator; const_iterator begin() const; const_iterator end() const; } 

But as you may know, I can't implement 2 functions with the same signature, so how may I solve thus?

6
  • 1
    why do you make iterator begin() const; ? why is it const? Commented Jun 12, 2020 at 20:58
  • because I shouldn't make changes to the member of my class (this) Commented Jun 12, 2020 at 21:02
  • usually, you make changes using it like inserting, erasing .... Commented Jun 12, 2020 at 21:04
  • If u erase/insert some data, the pointer pointing your data may point to a new dynamic array. Commented Jun 12, 2020 at 21:07
  • Your class should have one const begin() and one non-const begin(). It makes no sense to have two const begin(). If you don't want a non-const begin() remove it completely. Commented Jun 12, 2020 at 21:16

1 Answer 1

4

Even if the function itself does not mutate the this object, if you want to have begin() both for iterator and for const_iterator, is to make the 2 function differs by the consteness, and so you should do something like this:

iterator begin(); const_iterator begin() const ; 

And let the compiler choose the best one (if this is const, that he will choose the second one, otherwise the first one)

And this actually make sense... if you have a iterator, you must have a instance of the class that is not-const, otherwise you would be able to build a iterator with a const collection, and so you would be able to mutate a const collection, that is not what you want

Sign up to request clarification or add additional context in comments.

6 Comments

But my professor said If a function won't make changes it should be declared as const or he will decrease points
maybe generic could be helpful here?
@smith and he is right, but in the iterator class you will probably have a constructor to call from the begin function, which will accept something like a pointer to your class, or something like that... that pointer will point to a instance not-const, and so if you mark the begin function const, you won't be able to call that constructor
@smith generics belongs to java... this is C++, and no, template won't help you in this case, or maybe, with a lot of boilerplate that you can avoid taking out that const
wouldn't this be considered as code duplication too?
|