Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating a list of inherited class c++

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

I'm trying to iterate that list and call the implemented function of each class, however, the code doesn't 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 doesn't compile, I'm getting the following error message (for the line listIter->foo()):

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

Any ideas why?

like image 277
Idanis Avatar asked Jan 22 '26 22:01

Idanis


1 Answers

You have to use the iterator this way: (*listIter)->foo()

like image 170
Dani Barca Casafont Avatar answered Jan 25 '26 13:01

Dani Barca Casafont