Assuming we have 2 simple classes like this:
UCLASS()
class ELEMENTAL_API UParentClass : public UObject
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "Info")
void Refresh();
};
UCLASS()
class ELEMENTAL_API UChildClass : public UParentClass
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "Info")
void Refresh();
};
then, if I want to cast a pointer to UParentClass
to a pointer to UChildClass
, like below:
void RefreshData(UParentClass* data)
{
const UChildClass* ptr = Cast<UChildClass>(data); // successful cast
ptr->Refresh(); // alwasy compile error here
};
I always end up with a constant pointer to UChildClass
. The problem is, I can’t call a function from that casted pointer. It won’t compile and shows this error:
cannot convert 'this' pointer from 'const UChildClass' to 'UChildClass &'
I believe it’s because it’s not allowed to do this on a constant pointer. Is it really like that?
Another question is, is there a way to cast a pointer to a non-constant pointer in UE?
Please note that I want to do safe-casting. So direct casting like this (ordinary C++ style):
const UChildClass* ptr = (UChildClass*)data;
is not preferable, because I don’t know if it will cause run-time error, if the casting failed, or if it will be casted to a pointer with invalid memory address. In other words, it might be more difficult to handle problems with ordinary C++ style casting.
But, if that’s the only way, then I’ll just have to accept it.