I asked a question earlier but it turns out my problem was not properly modeled by my example. So here is my actual problem:
A
, and c
Edit: This answer the first version of the question, now see instead dasblinkenlight's solution.
If you do:
A* b = B();
Then *b
will be of type A. That's what you are doing in your for cycle. There's no "virtuality" or polimorfism involved in this.
The following code gives the behaviour you are looking for:
class A {
public:
virtual void bar() { std::cout << "This is an A" << std::endl; }
};
class B : public A {
public:
virtual void bar() { std::cout << "This is a B" << std::endl; }
};
int main(int argc, char **argv) {
std::list l;
l.push_back(new B());
l.push_back(new B());
l.push_back(new A());
l.push_back(new B());
for (std::list::iterator it = l.begin(); it != l.end(); ++it)
(*it)->bar();
}
Taking my example above, in that case:
b->bar();
will print This is a b
.