Download

TSubclassOf upward cast

I have two classes A and B, B is inherited from A:

UCLASS()
class A
{

}

UCLASS()
class B:A
{

}

now I’m having a function take a parameter of TSubclassOf<class A>
//declare of function
foo( TSubclassOf<class A> varClass )

However, I want to pass the parameter as TSubclassOf<class B>

//declare of varClass
UPROPERTY(…)
TSubclassOf<class B> varClass

//try to call foo by this variable
foo( varClass )

the compiler will send err:
error C2440: ‘initializing’ : cannot convert from ‘B*’ to ‘A*’

How should I avoid this? Since I found it really convenient of declaring varClass as TSubclassOf<> instead of UClass*.
I will prefer using TSubclassOf<> if I can solve this question.

Will this help at all?

No, what I’m trying to do is pass it as a parameter.
I don’t want to access any of its variable or function.

The best way I can thought is to modify the declaration of function, while keeping the variable type.

You can’t really cast TSubclassOf<> because it’s still pointer to UClass*, not YourClass*, and YourClass does not derive at any point from UClass.

It should work completely fine, since any TSubclassOf can be implicitly converted to UClass*. I just did a quick test and got no errors. In fact a quick look at the docs shows there is even a templated copy-constructor taking any TSubclassOf argument.

I’m guessing you just have a problem with your class declarations. Perhaps at the point you call the function one of the classes has only been forward declared or something?

yes, you are right!

Got no error at all if I include the header file.

Really appreciate your help.