user13707437
user13707437

Reputation:

How to implement const iterator?

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?

Upvotes: 1

Views: 282

Answers (1)

Alberto
Alberto

Reputation: 12899

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

Upvotes: 4

Related Questions