ArrayList type Array in C++

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)

Here's an example using std::vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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();
}
Also note that, in exception free environments, you can check the result of the dynamic casts, like so:
1
2
3
4
5
6
7
8
if( a = dynamic_cast<ChildA*>( myarray[1] ) )
{
    // it worked
}
else
{
    // it didn't work
}


Otherwise, I think an exception is thrown.
Last edited on
iirc exceptions are only thrown when you dynamic_cast a reference. They're not thrown for pointers.
Topic archived. No new replies allowed.