Question about the "cast" function

I don’t think I understand what we are doing by using the cast function. At 2:40 in the lecture, Sam says that we are using it to “check that the USceneComponent is actually a UPrimitiveComponent”.

Before posting this question I did a little bit of searching and what I found was all the explanations described casting as a “conversion” of one type to another, which seems to be different from what says stated.

Regardless whether it’s a check or a conversion, I’m not understanding why we can state that a "USceneComponent " is actually a “UPrimitiveComponent” because they aren’t, right? Does this have to do with the Inheritance/Composition concept, were you are saying an object “is a”, or “has a”?

Thanks!

You should search dynamic casting to get better search results about what is happening here.

You’re checking whether the object at the address is a UPrimitiveComponent. As a USceneComponent can point to objects of derived types as well (so yes re: inheritance).

A UPrimitiveComponent is a USceneComponent so it can be safely upcasted. however the reverse isn’t true. So down casting is not implicit as it’s not safe to do so. i.e.

struct Animal {};
struct Dog : Animal{};

Dog dog;
Animal* animal = &dog; // 👍
Dog* dog_ptr = animal; // ❌ (even though we can see it is directly above)

That is what Cast does, it performs runtime type checking. It will check the type of the object at the address; if it is of that type you specify you get the same address back, otherwise nullptr is returned.

Small demo: Compiler Explorer

Note: dynamic_cast is how you do it in standard C++ and it requires the class to be polymorphic which means having at least one virtual function.

2 Likes

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms