0
votes

As i am given to understand, the const specifier at the end of a member function means that the class's members cannot be modified, within that function, unless they are declared as mutable. Having said that i have the following:

mns::list::list is a linked list implementation of mine which functions are not const.

template<typename T> class HashTable{
private:
      std::vector<mns::list::list<T> * > * hashtable;
      long long int size;

public:
        HashTable(int _size){
             hashtable = new std::vector<mns::list::list<T> * >(_size, NULL);
             size = _size;
       }
        ....

       bool insert(T _value) const {
             long long int hash_value = getHash(_value);

             if (hashtable->at(hash_value) == NULL) hashtable->at(hash_value) = new mns::list::list<T>(_value);
             else if (hashtable->at(hash_value)->find_forward(_value) == -1) hashtable->at(hash_value)->push_top(_value);
       }

       ....
}

and i have a function in my main:

void testhash(){
       HashTable<int> testhashtable1(100);
       std::cout << testhashtable1.find(45) << std::endl;
       testhashtable1.insert(45);
       std::cout << testhashtable1.find(45) << std::endl;
}

Given that HashTable::insert is a const function i assumed that i wouldn't be able to modify private member hashtable. But testhash() prints:

0

1

which means the member was modified... right? So i seem to miss something here... Why was the private member vector hashtable modified?

3
long long int is very old way to write intmax_t or ssize_t. But if you want a size maybe it's better to have a unsigned integer ? like that uintmax_t or size_t. And you can have size of a vector with size methodStargateur
@Stargateur ssize_t is not part of the standard. size_t is.user1593881

3 Answers

4
votes

Your data member is a pointer to a vector. In the const member function insert all data members will be const, so your data member is now considered a const pointer to a vector. Since you do not try to modify the pointer itself (e.g. hashtable = nullptr) but the vector pointed to by it, the vector will be modified.

1
votes
  • a const pointer to some type

  • a pointer to some const type

they are totally different

0
votes

The const specifier for member functions allows that function to be called if the object is const. Therefore the function is not allowed to modify members or call non-const member functions.