An updated way to spawn an object using c++

I’ve looked around and seen that users used to spawn an object using the following:

UPROPERTY()
TSubobjectPtr Cube;

Cube = ObjectInitializer.CreateDefaultSubobject(this, TEXT(“Cube”));
Cube->bHiddenInGame = false;
RootComponent = Cube;

GetWorld()->SpawnActor(ACube::StaticClass());

However when I try and recreate this
UBoxComponent* Cube;

and then copy the code above into the contractor I get an error saying

'Use ‘template’ keyword to breast ‘CreateDefaultSubobject’ as a dependent template name.

All I really want to do is spawn a cube in the scene.
Any ideas?

Also. I have tried the following way as well:

In the .h:

UPROPERTY(category = Meshes, VisibleAnywhere)
UStaticMeshComponent* CubeMesh;

TSubclassOf Terrain;

//ERROR: c++ requires type specifier for all declarations;
ACubeActor(const FObjectInitializer& ObjectInitializer);

In the constructor(cpp):

//Redeclaration of constructor;
ATerrain::ATerrain(const FObjectInitializer& ObjectInitializer): Super(ObjectInitializer)
{
PrimaryActorTick.bCanEverTick = true;

CubeMesh = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("CubeMesh"));

static ConstructorHelpers::FObjectFinder<UBlueprint>    CubeBP(TEXT("Blueprint'/Game/BP_Cube.BP_Cube'"));

if(CubeBP.Object)
{
    Terrain = (UClass*)CubeBP.Object->GeneratedClass;
}

}