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
2010-07-22 08:58:52
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
2010-07-22 09:16:52
Yes, when you want to add the derived class object to the list you cast it to base class pointer.
user35467
2010-07-22 09:20:16
+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
2010-07-22 09:00:13
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
2010-07-22 09:17:37
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
2010-07-22 10:29:38
+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
2010-07-22 09:03:29
+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
2010-07-22 09:12:43