Can someone tell me and provide a code example of whether it is possible to create an array that can hold any types of objects without using inheritance in c++? I haven’t written any code for it yet, but for example if I have 2 classes: RangedWeap and MeleeWeap, is there a way to store these objects in the same array without using inheritance?
Share
If you want to store objects, no. The reason for this is that arrays store objects in contiguous memory, and the size of each stored object is identical. This doesn’t necessarily hold for different types.
There’s an ugly way of doing it storing
void*, but that would be storing pointers, not objects. Also, it would be useless, as all type information is lost. How in the world could you determine what thevoid*points to (assuming you don’t have a base class)?