Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of Child objects to a function that accepts Parent*

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?

like image 951
Rev Avatar asked Apr 28 '16 12:04

Rev


1 Answers

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;
}
like image 147
Marko Popovic Avatar answered Oct 02 '22 21:10

Marko Popovic