It's not possible to create an array of references in C++.
It is possible to create an array of pointers to A
, however. In that case, provided A
declares at least 1 virtual function, you could use C++'s run-time type inference (RTTI) mechanism to do what you want to do:
A* arr[10];
fill_with_as_bs_and_cs(arr);
for (int i = 0; i < 10; ++i) {
if (dynamic_cast<C*>(arr[i])) {
arr[i] = 0; // You can't really "remove" things from an array...
}
}
However, this is not the most maintainable approach -- any time you need to distinguish a C
from an A
, you'll need to use this if
test, and if you wind up deriving more classes from A
and you also need to treat them differently, you'll need to update every place in your code where you are performing this "type testing." As your codebase gets bigger, it quickly gets easy to miss places.
Generally, it's much more maintainable to use a virtual function that is overridden in each class as necessary. In this particular case, establish what are the general criteria shared by all A
-derived class objects that should be removed from the array -- let's say that an object should be removed if it is blargable -- and then write a virtual function bool isBlargable()
, and test that instead.