Let's say I have two abstract classes, A1 and A2. A1 has a function called foo(), A2 has a function called bar(). I create many different child classes of these base classes, say C1,C2,C3,..., that may or may not inherit A1 and/or A2. I now want to loop over all classes of type A1 and all classes of type A2 and call foo() resp bar(). My question is what is the best way to achieve this? My approach would be to use either smart pointers or vectors that hold instances of C1,C2,..., ie:
std::vector<C1> c1s;
std::vector<C2> c2s;
std::unique_ptr<C3> c3;
...
I then declare two integers, n_A1 and n_A2 that specify how many instances I have of each abstract class A1 and A2. I then define two arrays of pointers:
A1 **a1s = new A1*[n_A1];
A2 **a2s = new A2*[n_A2];
and then manually add all the addresses of the instances to these arrays. For example, if c1s has length 2, c2s has length 3, and if C1 inherits A1, C2 inherits A2, C3 inherits A1 and A2 I would do:
a1s[0]=&c1s[0];
a1s[1]=&c1s[1];
a2s[0]=&c2s[0];
a2s[1]=&c2s[1];
a2s[2]=&c2s[2];
a1s[2]=c3.get();
a2s[3]=c3.get();
So thus n_A1=3 and n_A2=4 and I can now loop over the arrays of addresses a1s and a2s and call the functions foo() or bar(). When deleting the instance holding all these objects, I just have to free the arrays a1s and a2s.
Being constantly recommended not to use raw pointers in C++, I wonder if this is a good way to solve this problem? Are there any risks with this approach? Is there a better way of doing this?
 
    