Download

How to pass in a TArray of a derived class in C++ functions?

Hey everyone, I’m running into an interesting issue. I’m unable to pass in a TArray of a derived class. For example, I made a C++ function in a blueprint library class that takes in a TArray<AActor*>, but if I pass in a TArray<derived class> (such as ABCPickupItem* in my example), it doesn’t work. I thought that this might not be something that is supported in the engine, but blueprints *do *allow it.

SpaceActorsEvenly.PNG


SpaceActorsEvenlyBlueprint.PNG

So, is this something that isn’t supported in C++ that blueprints handles behinds the scenes? Am I doing something wrong? Of course, I could always iterate through the array and cast back to the base class, but that doesn’t feel good for a helper function.

Can you paste your class definition for ABCPickupItem? Assuming it is actually inheriting from AActor you can just define ObjectivePickupItems as TArray<AActor*> or cast it to that when passing it to your function.

TArray<AActor>* and TArray<ABCPickupItem>* are two different types.

TArray provide copy/move constructors which allow converting related types



TArray<ABCPickupItem*> Pickups;
// Copy-constructor
TArray<AActor*> Actors(Pickups);

// Move-constructor
TArray<AActor*> Actors(MoveTemp(Pickups));


All you need to do is include the header for ACBPickupItem where you’re trying to pass it into that function. It doesn’t know what it is, so it can’t treat it as an actor in that case.