Different Structures in One Array [C++]
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?
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];}
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:
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!!
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!!
Quote:Original post by pTymN
std::vector<void *>
:-D!!! *bad tim bad tim*
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement