Inserting Different Types of Objects in a STL List

Inserting Different Types of Objects in a STL List

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?

STL containers and algorithms rely on strict static typing. This means that they do not support polymorphism (at least not directly).

A vector may store only Base objects. Trying to store derived objects in it will cause slicing and other unexpected surprises. The closest you can get to such polymorphic behavior is by using a container of pointers: vector . Because every object pointer has the same size, it’s OK to store a pointer to a derived object in a vector.

When you call a virtual member through a pointer stored in the vector, you get the desired polymorphic behavior:

 vector vb;vb.push_back(&derived);vb[0]->virt_func();


Share the Post: