Question

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.

Was it helpful?

Solution

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;
};

OTHER TIPS

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.

Declare it mutable, not volatile.

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 versus volatile. I got volatile confused with mutable. Thanks again!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top