Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if A is a subclass of B?

I am currently using Unreal Engine 4 and it seems that I can't avoid some casts.

AController* c = this->GetController();
APlayerController* p = (APlayerController*)c;

Is there a way that I can check if c is a PlayerController before I do the cast?

like image 416
Maik Klein Avatar asked Mar 24 '14 12:03

Maik Klein


People also ask

How do you check if an object is a certain subclass?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

How do you know if a class is subclass of another class in Python?

Python issubclass() This function is used to check whether a class is a subclass of another class.

How do you check if a class is an instance of another class?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .


1 Answers

Like a lot of game engines, Unreal Engine is compiled without RTTI for performance reasons, so dynamic_cast will not work.

Unreal Engine provides its own alternative, simply called Cast. I can't find any documentation for it right now, but this question describes its use nicely.

AController* c = this->GetController();
APlayerController* p = Cast<APlayerController>(c);
if (p) {
    ...
}

AController also has a convenience method CastToPlayerController which will do the same thing:

AController* c = this->GetController();
APlayerController* p = c->CastToPlayerController();
if (p) {
    ...
}

If you are sure that c is always going to be an APlayerController then CastChecked is more efficient:

AController* c = this->GetController();
APlayerController* p = CastChecked<APlayerController>(c);
...

In debug builds, this will use Cast and throw an assert if it would return null; in release builds, it resolves to a fast static_cast.

like image 60
Oktalist Avatar answered Sep 20 '22 22:09

Oktalist