Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

Inserting Different Types of Objects in a STL List

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

 

 

 

 

 


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

 

 

Sitemap