How would one create an array which holds any item that derives from a certain class?

I have a TArray inventory which holds an “Item” struct. Inside the struct, upon construction, I’d like to create an instance of the actor picked up in game. This item could be AWood, AStone, ASpear, but will have a common child of AItem*.

Without casting the in game object to an AItem, how can I “dynamically(?)” add any item that inherits from AItem into the struct?

My Speculation is that some template, class or solution exists as this seems an immediate issue one would run in to.

When you say a common child, I believe you meant a common parent. AWood, AStone, ASpear all inherit from AItem right?

Not sure if I got what you’re trying to do, but in that case you just need to store a pointer to a AItem as such:


    FItem() { ItemInstance = nullptr;}
    FItem(AItem* itemInstance) { ItemInstance = itemInstance;}
	/**AItem stored inside struct*/
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item")
	AItem* ItemInstance;


That way when you a construct it on blueprint or c++ you can always specify the AItem on construction, obviously it will only accept AItem references, not global Actors since this would probably result in sometimes the instance being set to nullptr again. but you could, at least on c++ add a constructor with a cast option:

FItem(AActor* itemInstance) { 
    AItem* i = Cast<AItem>(itemInstance);
    if(i){ ItemInstance = i; }
    else{ ItemInstance = nullptr;}

Or did you mean you want to spawn the ItemType(The AItem instance itself) on struct construction?