Iterate over a list of an inherited C ++ class

I have two classes that inherit from the third class, and they are stored in a list.

I am trying to iterate over this list and call the implemented function of each class, however the code does not compile.

Here is my code:

class A
{   
   public:

   virtual void foo ()=0;
};

class B :public class A
{
   public:

   void foo();
}

class C :public class A
{
   public:

   void foo();
}

std::list<A*> listOfClasses;

listOfClasses.push_back (new B());
listOfClasses.push_back (new C());

for(std::list<A*>::iterator listIter = listOfClasses.begin(); listIter != listOfClasses.end(); listIter++)
{
    listIter->foo()
}

This code does not compile, the following error message ( for the line listIter->foo()) appears :

'foo' : is not a member of 'std::_List_iterator<_Mylist>'

Any ideas why?

+3
source share
4 answers

There are pointers in your container, so you need to remove the link:

(*listIter)->foo();
+2
source

You should use an iterator as follows: (*listIter)->foo()

+5
source

You need to dereference the iterator first:

(*listIter)->foo()
+3
source

For some variation, here is a simpler alternative syntax for C ++ 11 that completely avoids this problem:

for (auto p : listOfClasses)
{
    p->foo();
}
+3
source

All Articles