How can I declare a derived class when declaring an array of its base class?

Hey guys, I have a class called Plane, with a few subclasses, roughly like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Plane{

public:

//blahblah

};

class Adiabatic : public Plane{

public:
//A few members class Plane doesn't have
};

class Thermal : public Plane{

public:
//Different members

};



So, at some point, I declare an array of the Planes, like so:

 
Plane * planeArray = new Plane[someInt];


But I want some of those Planes to be Adiabatic Planes, or Thermal Planes. Unfortunately, I won't know which until runtime. How can I make certain planes in that array members of a derived class?

Thanks!
Last edited on
That's not possible.
You need an array of pointers to Plane (or rather, a boost::ptr_vector).
As Athar says you need an array of pointers. I recommend you consider using std::vectors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>

// ... stuff ...

std::vector<Plane*> plane;

plane.push_back(new Plane); // add the pointer to a new Plane to the vector
plane.push_back(new Thermal); // add the pointer to a new Thermal to the vector

// Accessing the planes

plane[0]->func(); // call function on Plane
plane[1]->func(); // call function on Thermal


This has the advantage that you don't need to know how many planes are going to be at the beginning.
Last edited on
A regular vector would not conform to RAII (in this case), so it is better to use boost::ptr_vector (or another ptr_vector implementation).
Edit: neither does a dynamically allocated array, of course.
Last edited on
Topic archived. No new replies allowed.