Why does CreateWidget c++ version not behave the same as Create Class BP function?

UPROPERTY(EditAnywhere, Category=“Categoryname”)
TSubclassOf<UUserWidget> WidgetBPReference;

Then,

UUserWidget* WidgetInstance = CreateWidget<UUserWidget>(GetWorld(), WidgetBPReference);
WidgetInstance->AddToViewport();

Before running the code, go to the details of your widget bp and set the reference. (I guess you have already done this)