Your pointers aren't initialized.
std::vector makes a copy of those pointers (they point to the same location) but there is no memory allocated.
So when calling elements[i]->func(); you try to call the function, but element[i] points outside of your memory space so your programm crashes.
Also note:
- elements contains a variable to get the size: elements.size()
use that to iterate through the elements instead of N (for ( int i = 0; i < elements.size(); i++ ) )
- std::vector contains a method to insert elements at the end: elements.push_back()
2 easy ways to solve this:
- allocate memory and initialize the pointer
1 2
P * parent = new P();
D * derived = new D();
- Or just create that pointers when appending the element vector