# Different Structures in One Array [C++]

This topic is 4763 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a few classes, which are all inherited from one base class, that are really closely related. I'd like to keep them all in one structure, instead of having seperate arrays of each. I know this is possible in MFC (linked lists), but I don't use MFC in my project. Is there an alternative way? I was thinking the following, though I see how it might not work: CBaseClass Objects[ 15 ]; CInheretedClassOne Inherited; Objects[2] = Inherited; That wouldn't be legal, now would it? Can someone tell me a way it would work?

##### Share on other sites
The only method open to you is pointers.

class base{};class derived: public base{};int main(){base* array[10];array[0] = new derived;delete array[0];}

##### Share on other sites
std::vector<void *>

##### Share on other sites
You can solve this using pointers.

Any inherited class is a type of its base class. Pointers understand this, and so you can use code like this:

class base{};class derived1 : base{};class derived2 : base{};Base* d1 = new derived1;Base* d2 = new derived2;std::vector<Base*> myObs;myObs.push_back(d1);myObs.push_back(d2);

Using std::vector, instead of arrays (which you should, you know, if you're using C++ - and if you're using inheritance, then you are).

Alternatively, something really cool I discovered recently (that I use for storing settings, like HINSTANCE, int and float variables all in the same place) is boost::any.

HTH,
Jim.

Edit : 3rd? Got to improve my typing speed!!

##### Share on other sites
Quote:

Gosh! A little bit hard :) But you are right, the STL is the way to go.

If A is your base class then you can use a
std::vector<A*>
It would be better than a plain void * array.

Regards,

Edit: b34t3n by 1337 guyz.

##### Share on other sites
I suppose if we are recommending good practices, vectors of smart pointers are the way to go.

You will need Boost or Loki

#include<boost/shared_ptr.hpp>#include<vector>...int main(){std::vector<boost::shared_ptr<base*> >  array;array.push_back(boost::shared_ptr<base*>(new derived));}