Vector of derived classes

Hi, hopefully someone can help me here.

I have three classes derived from an abstract base class, and I want a single vector to hold objects of each of the three derived classes. Is it possible to do this?

I'm thinking along these lines:
1
2
3
4
5
6
7
8
vector <base> list;
der1 myder1('x');
der2 myder2('y');
der3 myder3('z');

list.push_back(myder1);
list.push_back(myder2);
list.push_back(myder3);


I'm pretty sure I need some pointers somewhere, so possibly this:
1
2
3
4
5
6
7
8
vector <base*> list;
der1 * myder1('x');
der2 * myder2('y');
der3 * myder3('z');

list.push_back(myder1);
list.push_back(myder2);
list.push_back(myder3);

Thanks in advance for any direction. :)
You have to use the second version.
Zhuge is right: you can't use direct copies of your base class.

But beware that using the second version will result in an awkward syntax. You will write things like this a lot: "(*iter)->". To fix this, look at boost (www.boost.org). It has very nice libraries for vectors of pointer. look at ptr_vector. It's worth the effort.

Ciao, Imi.
Last edited on
Topic archived. No new replies allowed.