Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Dec 1, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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;
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date