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();

See also  5 Ways to Improve Customer Experience

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist