Inheritance and lists

Hi all,
I have an object Field that is extended by two other classes; polarField and metricField. I want to store instances of these objects in a list, but at compile time I do not know if the list will contain polarFields or metricFields so I'm initilising the lists something like this:
1
2
3
4
5
   Field* list;
   if(x)
      list = new polarMap[capacity];
   else
      list = new metricMap[capacity];

However, when I print out the elements from the list, a lot of them seem to be corrupted and if I have to expand the size of the list then the contents are completely lost.
1
2
3
4
5
6
7
8
9
   if(index >= *fieldCapacity)
   {
      Field* largerList = new polarField[*fieldCapacity+5];
      copy (fields,fields+*numFields,largerList);
      delete [] fields;
      fields = largerList;
      *fieldCapacity += 5;
   }
   fields[index] = polarField(parameters);

Is there a better/safer way of doing this that will actually work?
Many thanks,
KU
You would need to have an array of pointers not of objects. That is:

1
2
3
4
5
6
Field** list = new Field*[capacity];
for(int i = 0; i < capacity; ++i)
{
  if(x)   list[i] = new PolarField;
  else    list[i] = new MetricField;
}


Of course you can simplify this with a container:

1
2
3
4
5
6
7
std::vector<Field*> list(capacity);

for(...)
{
  if(x)   list[i] = new PolarField;
  ...
}


If you don't mind going using other libs like boost, you can go one step further and make a ptr_vector so that cleanup is automatic.
Thanks Disch!
I will have a go using the vector container as this will probably solve some of the other problems I've been having too.
Topic archived. No new replies allowed.