You don’t have to use the UE4 templated cast function, but it is much safer.
This is all about up-casting vs down-casting and type safety. There is some type safety stuff that happens with up-casting because it can be automatic. You can always cast a AActor to a UObject automatically but you obviously can’t automatically cast a UObject to a UComponent because it could actually be an AActor or even a UMaterial!.
Because down casting isn’t so easy, you use explicit casting like Cast<UBaseclass>() or the C raw pointer cast (UBaseclass*). The issue with the normal C cast is that it does not perform any run-time type checking, it simply tells the compiler that you want the pointer to be treated as a pointer of some other type. This works fine if you know the pointer is always going to be pointing at an object of the type you are expecting, but what happens if it’s not?
In comes the Cast template function. How this works is that it uses the UE4 reflection information to verify that the type you want to cast to is in fact something that is allowed. If it is not, it simply returns nullptr.
An example of where this is handy is in the AActor::RecieveHit(). Say the actor is a energy bolt cast from a spell. Now this spell only deals damage to Trolls so in RecieveHit() on your spell bolt you can write something like this:
ATroll* troll = Cast<ATroll>(Other);
if (troll != nullptr)
{
troll->KillTroll();
}
If you were to use the normal C cast like this.
ATroll* troll = (ATroll*)Other;
And the actor you hit was a wall. The troll pointer would not be null and then when you call KillTroll(), the game would probably crash.
There is also a variation of CastChecked() which will assert if the type cannot be cast to. It is useful for making sure that higher level code is providing you with the correct inputs.