Say I have these structs:
struct Base{
...
}
struct Derived:public Base{
//everything Base contains and some more
}
I have a function in which I want to duplicate an array of these and then alter it.
void doStuff(Base *data, unsigned int numItems){
Base *newdata = new Base[numItems];
memcpy(newdata, data, numItems*sizeof(Base));
...
delete [] newdata;
}
But if I used this function like so:
Base *data = new Derived[100];
doStuff(data, 100);
It wouldn’t work, would it? Because Derived1 is larger than Base, so allocating for Base is not enough memory?
You could do this easily with a template:
Edit as per the comments: If you wanted to do this for a mixed collection things will get more complicated quickly … one possible solution is this: