Why do you do CreateDefaultSubobject<UPawnMovementComponent, UFloatingPawnMovement>?

Hi!

I don’t understand this piece of code: CreateDefaultSubobject<UPawnMovementComponent, UFloatingPawnMovement>. I create a UFloatingPawnMovement and return it as a UPawnMovementComponent.

If UFloatingPawnMovement inherits all public and protected methods from UPawnMovementComponent:

Why someone want to do this?

1 Like

Hi VlaCognlta,

The reason why it returns the Base class type is because it can be extremely useful to have “derived” classes (subclasses) that over-ride methods in the base class - you can pass the BaseType class into your functions with the new subclass and those over-ridden methods will be called. You can also “Cast” that base class to your subclass where needed (and you know that’s what it is) and call any new methods you have created in it.

2 Likes

I guess the question was why CreateDefaultSubobject<UPawnMovementComponent, UFloatingPawnMovement> if CreateDefaultSubobject<UFloatingPawnMovement> would be sufficient, since UFloatingPawnMovement derives from UPawnMovementComponent.

1 Like

BTW I’ve just tried specifying two related classes in CreateDefaultSubobject. It crashes the editor.

From DefaultPawn.cpp Unreal’s class, line 45:

MovementComponent = CreateDefaultSubobject<UPawnMovementComponent, UFloatingPawnMovement>(ADefaultPawn::MovementComponentName);

I don’t know what you did, but this code is part of the engine.

1 Like