Download

Small explanatory question "Cast" in C++

Hello friends of the code. Relatively new to C++.

Can anyone explain to me exactly what “cast” is good for in C++, using this example or in general?

I am in an actor “weapon”.

APawn* OwnerPawn = Cast<APawn>(GetOwner());

AController* OwnerController = OwnerPawn->GetController();

FVector Location;

FRotator Rotation;

OwnerController->GetPlayerViewPoint(Location, Rotation);

A Cast tells the compiler to treat a pointer as being a specific class.

In your example, GetOwner() returns an AActor. This AActor may or may not be a APawn.

The cast tells the compiler to treat the pointer returned by GetOwner as an APawn.

Thanks for the answer, and why would you do that? What is casting good for?

Because without casting in this case, you wouldn’t be able to call functions from APawn or access it’s properties.

I think I have understood the hierarchy and meaning of Cast.

Is there a page where you can see hierarchically all classes correctly assigned?

Use Documentation:

Inheritance Hierarchy:
APawn: APawn | Unreal Engine Documentation

Unfortunately there is no general view.
I also had the impression that classes are arranged next to each other. That is still missing. But thanks.

Cast here will check a class id for object and will compare a class id of the template class argument. If they have a match (i mean if one inherits another) - then a static_cast will be performed. It is like a dynamic_cast in c++. But unreal engine works without rtti and that is why it has a custom implementation.
google dynamic_cast and rtti for more information.