views:

128

answers:

2

Hi All,

Having problems iterating. Problem has to do with const correctness, I think. I assume B::getGenerate() should be const for this code to work, but I don't have control over B::getGenerate().

Any help is greatly appreciated.

Thanks in advance, jbu

Code follows:

int
A::getNumOptions() const
{
   int running_total = 0;

   BList::const_iterator iter = m_options.begin();

   while(iter != m_options.end())
   {
      if(iter->getGenerate()) //this is the line of the error; getGenerate() returns bool; no const in signature
      {
         running_total++;
      }
   }

   return running_total;
}

1>.\A.cpp(118) : error C2662: 'B::getGenerate()' : cannot convert 'this' pointer from 'const B' to 'B &'

+3  A: 

Well, if getGenerate is non-const, your iterator must be non-const. And if that's the case, your getNumOptions will also have to be non-const.

If getGenerate isn't under you control, there isn't anything else you can do. But if that method could be const, bring it up with whoever implemented that method; tell them it should be const.

GMan
thanks! duh. I get your explanation and had a feeling it was that...I just (for no reason) thought I had more control over whether the methods that I wrote were const or not.
jbu
+1  A: 

B::getGenerate() needs to be declared like this:

class B
{
   bool getGenerate() const;
};

The 'const' keyword is the important bit here. This tells the compiler that calling getGenerate() will not modify any of the other members of B.

Dan Olson