mirokai
mirokai

Reputation: 125

const_iterator over referenced list of pointers

There is a thing I really can't understand. Following Situation:

Test.h file:

class Test{
    public:
        const std::list<Item*>& getItems() { return m_items; }
        void showSomething() const;
    private:
        std::list<Item*> m_items;
}

Test.cpp file:

void Test::showSomething() const{
    for (std::list<Item*>::const_iterator item_it = getItems().begin(); item_it != getPlayers().end(); item_it++) {
        doSomething();
    }
}

Visual Studio tells me, that this doesn't work and underlines getItems() in the for loop. The error translates something like "type qualifier is not compatible with member function getItems ... the Object is const Test".

I know that getItems() returns a const reference to the list of Item-Pointers. But why can't I use it in the for loop?

Upvotes: 0

Views: 55

Answers (1)

Radosław Cybulski
Radosław Cybulski

Reputation: 2992

You missed const.

Try this:

const std::list<Item*>& getItems() const { return m_items; }

You need const, because showSomething method, from which getItems is called is const.

Upvotes: 2

Related Questions