My code is below and i am having an error with numberCollisions += collisionNum; The error states, 'numberCollisions' cannot be modified because it is being used through a const object. Is this error just popping up because it is a const function? Thanks for the help.
int HashTable_qp::findPos( const string & x ) const
{
    /* 1*/      int collisionNum = 0;
    /* 2*/      int currentPos = myhash( x, array.size( ) );

    /* 3*/      while( array[ currentPos ].info != EMPTY &&
        array[ currentPos ].element != x )
    {
        /* 4*/          currentPos += 2 * ++collisionNum - 1;  // Compute ith probe
        /* 5*/          if( currentPos >= array.size( ) )
            /* 6*/              currentPos -= array.size( );
    }
    numberCollisions += collisionNum;
    /* 7*/      return currentPos;
}
  • 2
    ¤ Yes, you're trying to modify a part of the object, which is logically const. Most probably that tells you that updating numberCollisions is not a right thing to do here. Alternatively, if it is right, then remove the const. In no circumstance should you make it mutable, or have a member pointer to it, or any such circumvention of the compiler's const checking, which is akin to just muting a nuclear power station's alarm horn. I'm mentioning that because you may get an answer or two recommending that. Cheers & hth.

3 Answers


Yes, exactly because of this reason. Constant method implies you won't change the instance, but you do, since your findPos is supposed to change the instance. So just remove const and move on.
Yes -- for something like this where you're modifying an internal bookkeeping number that doesn't affect the logical state of the object, you may want to consider defining the variable with the mutable qualifier:
class HashTable_op { 
    mutable int numberCollisions;

};
Yes, that's the reason for the error. To make the compiler shut up in such cases, you can mark the member mutable. However I 'm not sure what exactly you are doing here and if making the compiler shut up would be the correct response.
The classic example scenario for using mutable would be the case where you perform an expensive but not mutating operation (therefore the corresponding function is const) but want to cache the results so that you don't have to do it again if the function is called immediately once more. You need somewhere to store the result, but the function is const; hence, mutable to the rescue.

Result

ex)  mutable int numberCollisions;

mutable 붙여주면 const 함수 내에서 수정 가능.
그러나 옳치않은 방법이므로 쓰지 않을수 있도록 구조자체를 변경하는게 더 좋은 방법.