Danny
Danny

Reputation: 9634

An array to hold any Objects in C++?

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?

Upvotes: 2

Views: 1146

Answers (3)

Shahbaz
Shahbaz

Reputation: 47583

You will have a hard time distinguishing between the two objects, but given you have a way for that, you can use a union:

struct A
{
    int type;  // to distinguish
    ...
};

struct B
{
    int type;
    ...
};

union AB
{
    int type;
    A a;
    B b;
};

AB array[] = {<whatever>};

Later, you have to check for type when you access, to know whether you should access a or b in each element.

Note: your objects should be POD, unless you are using C++11 according to @chris.

Upvotes: 0

Steve M
Steve M

Reputation: 8526

Boost.Any will enable this, but it (probably?) uses inheritance under the hood, if you care.

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258638

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 the void* points to (assuming you don't have a base class)?

Upvotes: 7

Related Questions