tags:

views:

85

answers:

4

can you add different class objects to same list?

A: 

Only if you derive the objects from the same base class and declare the list of base class type.

Felics
This is wrong - if you declare std::list<base_t>, you cannot store objects of some derived type in that list. As Naveen says, you have to use something like std::list<base_t*> instead. One reason for this is because a derived type may have more member data fields, and therefore not fit in the space reserved for a base_t instance.
Steve314
Yes, when you want to add the derived class object to the list you cast it to base class pointer.
user35467
+5  A: 

See boost::any.

You can use std::vector and then use it to add heterogeneous types into.

Example:

std::vector<boost::any> v;
v.push_back(std::string("hello world"));
v.push_back(42);
Scharron
At last a reason to learn boost library.
user35467
If you want to go further, have a look at boost::variant. It's more a compile time version of boost::any, with compile-time checking. boost::any is more or less the dynamic way to do the same, with type checking done at runtime.
Scharron
Yep since any has no knowledge about the possible types, there is no way to get the type of the stored object. One has to know it in advance to access the value. With variant, the variant would tell you already, which is a big benefit.
Johannes Schaub - litb
+2  A: 

No, if they are unrelated objects. If they are related (i.e. have a common base class) then you can store the base class pointer (use smart pointers instead of raw pointers) in the list.

Naveen
+2  A: 

Technically, you could store void * pointers to objects in your list, but generally it's not a good idea. Better use some "variant" class, such as boost::any or QVariant (if you're using Qt) that will wrap your elements.

el.pescado