k_kaz k_kaz - 4 months ago 26
C++ Question

const member function mutable

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{
std::vector<mns::list::list<T> * > * hashtable;
long long int size;

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



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


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.