Casting from APawn* to MyCustomCharacter* ? Is this ok?

So I am still learning C++ but been using it for quite a while. But I have a function which is not working properly (separate question posted here: Calling Client RPC in order to assign a Team value to clients. How to check the Role properly? - Development Discussion / Multiplayer & Networking - Unreal Engine Forums).

I am starting to think the problem MIGHT be about how I cast from the APawn* to APlayerMallet* (which is actually extending ACharacter not APawn).

APlayerMallet* mallet=(APlayerMallet*)gamestate->PlayerArray[i]->GetPawn();

The code compiles and it does find the function in APlayerMallet if I change the IF statement to force it to call the function in APlayerMallet.

I suppose here I am just looking for confirmation that it is ok to do such a cast.

Thank you for any help

1 Like

Do not use the old C-style cast. The preferred way would be

APlayerMallet* mallet=Cast<APlayerMallet>(gamestate->PlayerArray[i]->GetPawn());

if(mallet) {
  mallet->SomeMethodSpecificToMallet();
}

This is a dynamic cast that makes sure that “mallet” is nullptr if it is not a APlayerMallet instance. Your example would crash if for some reason GetPawn() returns something else.

Thank you very much for this info

ACharacter is a subclass of APawn, so all APlayerMallets are also APawns (and ACharacters)