views:

503

answers:

5

Is there a way to declare an iterator which is a member variable in a class and that can be incremented using a member function even though the object of that class is const.

+7  A: 

That would be with the "mutable" keyword.

class X
{
public:
   bool GetFlag() const
   {
      m_accessCount++;
      return m_flag;
   }
private:
   bool m_flag;
   mutable int m_accessCount;
};
James Curran
This will work for integers but if it is an iterator to a list or a map it doesnt work on const objects. It throws error at iter = list.begin() saying no "=" operator available.
@tmpforspam: Without being able to see the complete error message you're getting, it sounds like "list" is also const and you should be using a const_iterator.
Shmoopty
+3  A: 

Declare it mutable, not volatile.

anon
+5  A: 

Are you sure you need iterator as a member? Iterators have an ability: they become invalid. It is a small sign of a design problem.

Mykola Golubyev
I want to iterate through a list using a member functions. getFirst and getNext kind of....But for that I want to declare a mutable iterator so taht I can iterate on const objects.
go for the STL-Design of iterators. It is accepted in the C++ comunity and would not suprise other developers. That would mean that the iterator is not part of the class.
Tobias Langner
@tmpforspam: if the behavior of your object changes when calling your member function, it's not a const function.
xtofl
A: 

Got it.

using namespace std;
class tmptest
{
    public:
    void getNextItr()const
    {
     m_listItr = m_list.begin();
     m_listItr++;
    }
    list<string> m_list;
    mutable list<string>::const_iterator m_listItr;
};

Mutable along with const_iterator works... Thanks for reminding me mutable vs volatile. I got volatile confused with mutable. Thanks again!!!

This is a serious breach-of-contract: after calling the `getNextItr()` function, client code will assume the object is still the same, but it's not.
xtofl
A: 

this article explains both Mutable and Volatile: http://cpptalk.wordpress.com/2009/09/16/mutable-and-volatile/

rmn