Getting parent class and properties

It’s one of those things that’s probably really simple but my brain just isn’t seeing it right now.

I’ve created an item class based off of AActor. I’ve created a C++ subclass from this item class but want to be able to access the components on the base class.

Here’s my code:

if (UClass* ParentClass = StaticClass()->GetSuperClass())
{
UE_LOG(LogTemp, Warning, TEXT(“Banana Parent Class is %s”), ParentClass->GetName())
if (AHDItems
* ParentActor = Cast<AHDItems>(ParentClass))
{
ParentActor->ItemMesh->SetCollisionResponseToAllChannels(ECR_Overlap);
UE_LOG(LogTemp, Warning, TEXT(“Banana Succesfully got parent class for %s”), *GetName());
}
else
{
UE_LOG(LogTemp, Warning, TEXT(“Banana Failed to get parent class for %s”), *GetName());
}
}

ParentClass is correctly being set but the cast is failing. I just don’t know why. I hope someone can help.

I think you’re having trouble understanding inheritance in C++. You item is based off of AActor, and it IS and AActor. You don’t need to “find the parent class”. A class is the type of object, and there is only one of each of your object. So, no casting is necessary.

There is no seperate “parent actor”, your object is a:

  • UObjectBase
  • UObjectBaseUtility
  • UObject
  • AActor

…all at the same time. It’s called polymorphism

So, instead of doing this:

if (AHDItems* ParentActor = Cast<AHDItems>(ParentClass))
{
    ParentActor->ItemMesh->SetCollisionResponseToAllChannels(ECR_Overlap);
    UE_LOG(LogTemp, Warning, TEXT(“Banana Succesfully got parent class for %s”), *GetName());
}

You need to do this:

ItemMesh->SetCollisionResponseToAllChannels(ECR_Overlap);

That’s it.

All of the properties, functions, and components from every parent class are available to your object (with the exception of private ones).

I hope this helps, I can explain more if you need it.

2 Likes

The UClass type is only for describing classes, not objects. So you can’t cast an object to a class or vice versa.

Thank you so much. I was very clearly overthinking that one and didn’t even consider I could just access all of the parent class components and variables without a reference. :+1:

That makes sense. Thanks for the clarification.

Glad I could help :smiley: