Hello, I am currently having a problem and am trying to find the best solution. This is what I am trying to do and my problem.
I have a base class with multiple derived classes. What I want to do is create an array (list) that can contain all of these different derived classes. If I make the array contain the base class I am able to put any of the derived classes into that array but they are cast to that base class and lose all of its unique data (which I obviously dont want). How should I go about to achieve what I am trying to do?
I have done some research and tried a few different methods but the best I could come up with is using System::Collections::ArrayList which I couldn't get to work. Any help is appreciated. Thank you
1) make an array of a pointer to the base class. These pointers can in fact be pointers to children classes as well. Allocate them with new and delete with delete
2) you can downcast to a specific child with dynamic_cast<> or static_cast<> (dynamic_cast<> is a little bit slower because it does runtime checks, but is safer because it will fail if the pointer is not actually of the requested type)
class Parent
{
public:
int p;
};
class ChildA : public Parent
{
public:
int a;
};
class ChildB : public Parent
{
public:
int b;
};
//...........
std::vector<Parent*> myarray;
myarray.push_back( new ChildA );
myarray.push_back( new ChildB );
ChildA* a = dynamic_cast<ChildA*>(myarray[0]);
// do whatever with 'a' here
a = dynamic_cast<ChildA*>(myarray[1]); // this will fail (a == NULL) because myarray[1] is
// a ChildB pointer, not a ChildA pointer
ChildB* b = static_cast<ChildB*>(myarray[0]); // this will not fail (b will be non-null)
// but it is errorneous! Because myarray[0] is not a ChildB pointer!
// only use static_cast if you are 100% sure you're casting right
// dynamic_cast is much safer
// to clean up:
while(!myarray.empty())
{
delete myarray.back();
myarray.pop_back();
}