Casting in Unreal Engine

What is “Cast<>()” in Unreal Engine. What is it’s functionality? Please make it simple.

It’s not a simple thing.

If you have something like CreateWidget<WidgetClass*>, this returns a UWidgetT* but is really returning a WidgetClass* which inherits from a different class which inherits from UWidgetT. If you just need to act on it using methods provided by UWidgetT then that is fine, but if you need the return type to be what you said , i.e. WidgetClass, then Cast<WidgetClass>(CreateWidget<WidgetClass>(.....)) would return a WidgetClass instead.

Now I know this is complex, but it’s all to do with inheritance in an Object Oriented language.

Now I’ll try and simplify.

if you have a class called Shape, then you create a class called Square you can cast and instance of Square to Shape and it will work fine.

Now imagine Triangle, Hexagon and Square all inherits from Shape and all implement a function called Area, which Shape has a virtual method which returns nothing. You can get a Shape of one of these types and treat them as Shape and call Area. This is called upcasting.

Downcasting is when you go the other way, i.e. you can do the following

Shape *s = new Square();
Square *square = Cast<Square*>(s);

So, to try and summarise, Cast<> tries to treat a class as another in its chain of inheritance.

It can go in either direction but you, as the coder, have to be absolutely sure it’s what you want to do because otherwise it can, and indeed it does, go horribly wrong.

Thank You.
You told where we use cast but why is it helpful? I mean, I have heard that we cast to assign and a variable to another variable of same type. For example “ACharacter* MyCharacter = Cast(Pawn* OtherActor)”. Here OtherActor will behave like ACharacter type if casting goes successful. Am I right?

Yes, basically that’s it. It is for methods that are used to search for a type and returns a UObject
but you really want it to be a PlayerController or something, for example. Cast does this. The returned item is really the right type and cast converts it.

Sometimes you want the UObject - this is fine too.

1 Like

What is UObject?

It’s a base class that most things in Unreal inherits from.