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?

Answers


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)?


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


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.


Need Your Help

Multiply two pre-defined values in the kernel

c parallel-processing opencl

Below is my kernel, but when i wanna multiply or do other operations with two values which are defined by #define keyword and assign it to an argument of the kernel i get an error with error status...

Twitter Streaming API with OAuth?

ruby-on-rails ruby twitter oauth streaming

I've been stuck on this for awhile. Does anyone know how to authenticate the Twitter Streaming API requests using OAuth? As of right now I'm authenticating via Basic Authentication, and I would lik...