Creating a reference to a C++ actor in another class causes crash: Access violation - code c0000005

I created a C++ Actor, which works fine on its own (i.e. if I spawn it in the editor somewhere in the world it works as expected).

I’m trying now to create it inside another C++ Actor, in the constructor., like this:

MySecondActor::MySecondActor()
{
     // I create the actor and set it as invisible. mMyActor is defined in the header as "MyFirstActor *mMyActor"
     mMyActor = CreateDefaultSubobject<MyFirstActor>(TEXT(test));
     mMyActor->SetActorHiddenInGame(true);
}

The code above works and the editor doesn’t crash if I spawn MySecondActor in the world. I would like now to manipulate the reference to MyFirstActor at runtime now, but ANYTHING I do to it makes the edtor crash.

For example, if I do this:

void MySecondActor::BeginPlay()
{
     if(mMyActor != nullptr)
         mMyActor->SetActorHiddenInGame(false);
}

It crashes when calling mMyActor.SetActorHiddenInGame(false) saying “Access violation - code c0000005 (first/second chance not available)”.
Note that it passes the check with the nullptr, so the reference is somehow valid.

Right now the class MyFirstActor is basically empty. I only use the constructor like this:

MyFirstActor::MyFirstActor()
{
    USceneComponent *sceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
    RootComponent = sceneComponent;
}

I haven’t a clue of what is going on here. Please, somebody help me!

You will want to do that kind of thing during runtime only. The constructors are actually ran in the editor, and your actor is not going to be valid in the editor, I would recommend doing it during BeginPlay.

You’re right, doing it in BeginPlay() solves the problem. Still, I would have liked to create it at compile time, but it will have to do. For anyone that stumbles upon this topic, I create the component like this in BeginPlay():

     FActorSpawnParameters spawnParams = FActorSpawnParameters();
     spawnParams.Name = TEXT("Something");
     spawnParams.Owner = this;
     spawnParams.OverrideLevel = GetWorld()->GetCurrentLevel();
     spawnParams.bAllowDuringConstructionScript = true;

     mMyActor = (AMyFirstActor*) GetWorld()->SpawnActor<AMyFirstActor>(ATranslationWidget::StaticClass(), FVector(0), FRotator(0), spawnParams);