You'll need to use pointers and use copy constructors. Oh and also, don't use the keyword struct
for more than basic data structures. Technically it works, but what you're creating is class hierarchy, so use the class
keyword.
This won't work simply because Derived is bigger and also is for intents and purposes a completely different object that is compatible with Base
mainly by interface, but more importantly, when dealing with classes, you shouldn't really use low-level memory manipulation. Instead, you should be setting up copy constructors and use libraries like < algorithm > to perform templated actions on them.
Further more, the reason why it won't work, despite being legal syntax (i.e. Base * = Derived *
), is that your allocating larger objects than what a Base *
would index into, which would lead to memory corruption by writing memory to the wrong location.
For example, if a Base
object is 4 bytes, C++ would index the array every four bytes, but if the actual allocated Derived
objects are 8 bytes then you're indexing halfway across object boundaries and your member variables won't be pointing to the right location in memory.
Using class hierarchies in an array:
Base *objects[100];
for (int i = 0; i < 100; i++)
objects[i] = new Derived();
Even further, to make things easier to manage, you may want to use a smart pointer mechanism and a template list instead of raw pointers.