How do I cast between polymorphic classes that don't extend UObject?

Hi, I have some classes I wrote that aren’t in any way related to UObject. I have a base class and a derived class that extends the base class. If I try to use dynamic_cast< Derived*>(Base*) I get this error:

error C4541: 'dynamic_cast' used on polymorphic type 'HandTracker' with /GR-; unpredictable behavior may result

I’ve done some research and I found out that Unreal Engine compiles without Runtime Type Interpretation which allows dynamic casts to work. Next I tried to use Unreal Engine’s built in “To* Cast< To, From>(From*)” function, but it appears that it requires the two classes To and From to be extensions of UObject.

What’s the best way to do this?

2 Likes

The correct way to do this is with StaticCast. Unfortunately, you, the developer, are responsible for making sure the type you’re casting to contains the object, and the engine may crash if the cast fails (instead of returning nullptr, like Cast does).

Turns out there’s a better way to do this (now?). Just add bUseRTTI = true; to your build.cs file.

From this post Where do I specify compiler options? - Pipeline & Plugins - Unreal Engine Forums

what are the implications for that though?

RTTI is a compilation flag in the compiler, enabling it may make compilation slightly slower, RTTI may not be a speedy runtime feature either. I don’t work for Epic so I’m not sure why they have it disabled by default when it’s enabled by default in other compilers.

Why can’t I use c++ style dynamic_cast? I mean they are base and derived classes.

Dynamic cast requires RTTI