Jump to content
  • Advertisement
Sign in to follow this  
_Camus_

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

This topic is 2810 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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?

Thanks

Share this post


Link to post
Share on other sites
Advertisement
It's not the iterator you want to be const, it's whatever the iterator is pointing to you want to be const.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!