Problem with const function

Hello++,

I'm trying how make a member function const. The code compile OK if the function is not const.

myclass.h:
----------
struct my_data {
int iVal;
double dVal;
};

enum SomeType : int {some types...};

class MyClass {
private:
std::map<SomeType, std::deque<my_data>> data;
std::map<SomeType, SomeClass*> objects;

public:
void dump() const;
};

myclass.cpp:
------------
void MyClass::Dunp() const
{
for (auto pos1 = data.begin(); pos1 != data.end(); pos1++) {
std::cout << (objects[pos1->first])->aConstFunction(); //<<fails here
for (auto pos2 = (pos1->second).begin(); pos2 != (pos1->second).end(); pos2++) {
// do something...
}
}
}

It fails with:
myclass.cpp: In member function ‘void MyClass::dump() const’:
myclass.cpp:137:61: error: passing ‘const std::map<SomeType, SomeClass*>’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = SomeType; _Tp = SomeClass*; _Compare = std::less<SomeType>; _Alloc = std::allocator<std::pair<const SomeType, SomeClass*> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = SomeClass*; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = SomeType]’ discards qualifiers [-fpermissive]
std::cout << (objects[pos1->first])->aConstFunction();

But if I change the dump() to be a non-const function, it compile OK.

How can I make the dump function const?
Last edited on
The way the subscript operator works for std::map is that if the element doesn't exist it will be automatically created. That means it can't be const because it might need to modify the map.

If you are sure the element is in the map you can use the at function instead. It will throw an exception if the element is not found.

 
std::cout << objects.at(pos1->first)->aConstFunction();

http://en.cppreference.com/w/cpp/container/map/at
Last edited on
Thanks! :)
Topic archived. No new replies allowed.