Sign in to follow this  

C++ Overload pre-post-increment with const type

Recommended Posts

Hi, i'm making my own list class with my own iterator class, for simplicity the const interator is just:

class Iterator;
typedef const Interator const_Iterator;

Iterator overloads post and pre increment (++), that works fine whith non-const iterator objects, but obviously didn't work with const iterator, because, is const, can't be modified, there is some way around this?


Share this post

Link to post
Share on other sites
A const_iterator isn't quite a const iterator:

typedef char* iterator;
typedef const char* const_iterator;
typedef const iterator iterator2;

char buf[128] = {};
iterator it = buf;
++ it; // Ok
*it = 'H'; // Ok

const_iterator it2 = buf;
++ it2; // Ok
*it2 = 'H' // Error

iterator2 it3 = buf;
++ it3; // Error
*it3 = 'H'; // Ok

Share this post

Link to post
Share on other sites
Ohhh good point!! thanks!

Now i have no idea how to implement a const iterator, because yesterday i had two classes, Iterator and const_Iterator, when my list class returns Begin() it should return Iterator AND also const_Iterator, but compiler says that i can't, thats why my "solution" was to typedef...

Anyone has a good reference on how to implement an iterator?

Share this post

Link to post
Share on other sites
Pointers have two types of const. Const on the pointer itself, meaning you can't change where it points, and const with respect to the data. Iterators need to provide the same functionality, but because they're not an actual pointer type, the const keyword affects the iterator itself and not access to the underlying data.

iterator and const_iterator are different objects, but c++ allows you to overload a function on const-ness alone.
Function declarations:
iterator begin();
const_iterator begin() const;

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this