Question:
I would like to know if it is possible to insert objects of different types in the same STL list.
I have an object A and two objects AB and AC that inherit A (overloading some methods), and I need to build a list of objects of type AB or AC, so that I can go through the list executing one of the overloaded methods without knowing which of them (A.method, AB.method, or AC.method) is executed.
How can I do this?
Answer:
STL containers and algorithms rely on strict static typing. This means that they do not support polymorphism (at least not directly).
A vector
When you call a virtual member through a pointer stored in the vector, you get the desired polymorphic behavior:
vectorvb;vb.push_back(&derived);vb[0]->virt_func();