Casting UStruct to derrived struct

From Copilot:

In Unreal Engine, casting is typically used with objects that are part of the UObject hierarchy. However, for structures (which are not UObjects), you can’t use the Cast<> function because it’s designed for UObject casting. Instead, you would use C++ casting operators such as static_cast if you’re certain about the type at compile time.

For example, if you have a base struct and a derived struct, and you want to cast a pointer or reference of the base struct to the derived type, you would do something like this:

FBaseStruct* BasePtr = /* ... */;
FDerivedStruct* DerivedPtr = static_cast<FDerivedStruct*>(BasePtr);

This assumes that BasePtr actually points to an instance of FDerivedStruct. If you’re not sure of the type at compile time and need to check at runtime, C++ offers dynamic_cast, but it requires that the base struct has at least one virtual function, making it a polymorphic type.

Since structs in Unreal Engine (USTRUCTs) don’t support polymorphism like classes do, you can’t use dynamic_cast. If you need runtime type checking, you might need to rethink your design or use other mechanisms, such as type identifiers within the structs.

Remember, improper use of casting can lead to undefined behavior, so it’s crucial to ensure that your casts are safe and that you’re casting to the correct type.

1 Like