Understanding casting

Hello. I’m trying to understand how casting works. Here are some input data(pseudo code)

Main class:

class PickableItem : public AActor
{

virtual void use();

}

Child class:

class PickabledWeapon : public PickableItem
{

virtual void use() override;

}

Somewhere else in code, I’ve used raytracing to get Actors in my view. In the end I have following code

PickableItem* item = Cast(Hit.GetActor())

item->use()

And here i have use() being called from my child class, even though i have casted to parent class. How did that happen?

PS I know how virtual functions work, and what is inheritance. What i dont know how does result of cast to PickableItem returns PickableWeapon

Casting only effect variable type not how class code is being executed (except non-virtual functions, which is still effect of changing the variable type). If you want to call parent’s overrided virtual function you need to call it with parent (or even grandparent) namespace

Item->PickableItem::Use()

Sorry, parsed ate some details
I have Cast"<“PickableItem”>"(Hit.GetActor()). But somewhy my use() function calls from its children class

Thats normal, thats how virtual functions work, regardless of type of variable being used the most highest overrided version of function will be called. It lets object maintain there behavior regardless of type being used, if you don’t want that then don’t use virtual function, or as i said in anwser if you want to call parent version of a function use namespace.

I understand, but isn’t providing class to cast - i specify what result do i expect to get? Because from my code - i get not exactly what i expected. Yes i can use parent function, but i want to understand why did i get not class i asked to cast to

You got class you asked for, if you would’t you would have compilation error because you can’t place PickableWeapon pointer to PickableItem pointer. Again, cast (or rether calling object from different type) does not effect the code of object and how it’s executed, it only effect type of varable, not the object itself.

As i said virtual function regardless of type you gonna cast to, it will call highest overrided version of function of object, not the casted type version that you seem to expect, that how virtual functions work. If you don’t want this behavior don’t use virtual function, or don’t use “override” keyword in function decleration. And this is not just in C++, but pretty much common behavior in must object oriented languages.

I think what mislead you are pointers, if you change type of pointer, it won’t change how object is constructed in memory, it’s still child object.