I am working on an embedded platform with limited capabilities, so vectors/STL are not available.
This may be a trivial problem, but I do not have much experience in C++ (only C and C#, which may make me blind to an obvious c++ way to do it).
Consider the following example:
class Parent {
};
class Child : public Parent {
};
void Test(Parent* parents, uint8_t parentCount) {
// Accessing parent[x] is problematic when 'parents' contains a derived type
}
int main() {
// This is OK
Parent parents[3];
Test(parents, 3);
// This causes problems
Child children[3];
Test(children, 3);
return 0;
}
Obviously it is problematic to iterate over parents in Test(), if a pointer to an array of derived classes is provided, because the memory footprint of Parent is assumed during the iteration.
The only solution I see is to pass an array of pointers of type Parent (Parent** parents), but that seems cumbersome. Is there some C++ mechanism I am not aware of, like passing the array as a reference or something?
You could use this approach:
template <class T>
void Test(T* parents, uint8_t parentCount) {
// Code that accesses parent[x]
}
and then use it like this:
int main() {
Parent parents[3];
Test(parents, 3);
Child children[3];
Test(children, 3);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With