How to put different structures in one array.

Sometimes, it is very cose to store objects of different types in the same array.
It’s possible then each objects types derived from one parent, and we can specify it as type of array elements.
As I see, structures don’t allow this.
Is it possible to put different structures in one array?
They are so good in all other respects.

You will want to create a struct that has the types of arrays in it that you want to store. So a struct within a struct. Structception if you will… either that or 3D array but i prefer my term

I want to put two structures in one array.
I can do it with objects, and I want same with a strtuctures.
Is it possible to choose base structure as array element type, or create untyped array?

You create a new struct that has the child structs as elements inside it. The same way if you put a vector or colour param inside your struct.

You can’t do an untyped array in blueprints.

Ok, thank you, I figured out what you meant. But this method does not seem to me good.
My choice fell on the structure because they have an auto make,
is it possible to get the same for the UObject derived substances?

Actually, you can use inheritance with C++ structs.

This should work in C++:

struct base { ... }
struct subA : base { ... }
struct subB : base { ... }

subA a;
subB b;
std::array<base*, 2> arr;
arr[0] = &a;
arr[1] = &b;

But I am not sure if you can pair that up with an USTRUCT of UE.
But what you want to achieve is possible with C++ at least (even if the snippet above may be faulty) - I know that for sure, if nothing changed in the past few years

If you try it out with USTRUCTs, please report wether it worked :smiley:

Edit: Oopsie, manoelneto is right. This does only work dynamically of course. You must store pointers, not variables!

Not going to work. When you create an array of objects, you’re actually creating an array of pointers to objects. Each item in the array has the same size: either 32 or 64-bits (depending on the platform), which contain the memory address where each object is located.

When you create an array of structs, the values of the struct are copied and stored in the array’s allocated memory, directly. Therefore, all items must have the same “type” (aka: the same size). Using inheritance will not work for arrays, because “struct subA” can be bigger, in bytes, than “struct base” and won’t fit in the array. At best you’ll cause a buffer overflow and corrupt other items in the array.

Struct inheritance, like class inheritance, is supposed to be used with pointers/references.

1 Like