TArrays with inherited objects problem

Hey guys,
dont understand what is wrong here.

I have following structure ABaseCharacter as a Base class, and APlayerCharacter : ABaseCharacter.

then I have two arrays, TArray<ABaseCharacter *> baseChars and TArray<APlayerCharacter *> chars.

Now if I try to do baseChars = chars,

compiler tells** no viable conversion from TArray<APlayerCharacter > to TArray<ABaseCharacter >…

I cant understand why, those two types inherited, why it doesnt understand that?

APlayerCharacter is already a class. So if you create a class with that name the compiled gets confused. Just to make you mad because you did the same to it.

Rename your own APlayerCharacter.

What you’re expecting here is that your array types are covariant, which is something that languages like C# and Java have implemented for their generic types. However, C++ templates are not generics and do not support covariance just like that. What you get in C++ is that your TArray<ABaseCharacter*> and TArray<APlayerCharacter*> classes are two completely separate copies of the TArray template with no direct conversion defined between them. You can still add an APlayerCharacter* to your TArray<ABaseCharacter*> because APlayerCharacter inherits from ABaseCharacter, but that doesn’t mean that the TArray<APlayerCharacter*> class automatically inherits from the TArray<ABaseCharacter*> class.

Thank you!

Just out of curiosity, which answer was the solution?

For future generations: the correct answer is Nico’s. C++ templates aren’t covariant, so even if the type parameters are derived, you can’t assign one to the other.