"Using incorrect object initializer" while initializing USpotLightComponent

So, I tried to add Flashlight to my First Person game:
.h file:

UPROPERTY(EditAnywhere)
		class USpotLightComponent* FlashlightComponent;

.cpp file:

FlashlightComponent->CreateDefaultSubobject<USpotLightComponent>(TEXT("Light"));

But after attempt to compile project, UE crashed, and here is screenshot:


Any ideas?

Where in the cpp file are you initializing the variable?? In the CDO?

Sorry, im very new into Unreal, what is CDO? If I understand right, and my charcter’s class name is AMyCharacterCPP, then CDO is AMyCharacterCPP::AMyCharacterCPP func. If so, yes, im initializing it in CDO.

Didn’t noticed you called CreateDefaultSubobject on FlashlightComponent…
FlashlightComponent is the object that is supposed to be initialized. You can’t call CreateDefaultSubobject because it doesn’t exist yet.

You need to call:
FlashlightComponent = CreateDefaultSubobject(TEXT(“Light”));

and you were putting it in the CDO (Class Default Object). It’s the part of code that in part resembles a pure c++ constructor where default values are set.
It has the same method name as the class so in your case
AMyCharacterCPP::AMyCharacterCPP though the passed in parameters can be different depending on implementation.

No, it didn’t work.

Copy + paste error (you need to set the return type)

FlashlightComponent = CreateDefaultSubobject<USpotLightComponent>(TEXT(“Light”));

|Error (active)|E0304|no instance of overloaded function AMyCharacterCPP::CreateDefaultSubobject matches the argument list

Double check your code…you literally have the same syntax 1 line above. Perhaps your quotation marks are wrong?

Also make sure your cpp has:
#include “Components/SpotLightComponent.h”

Yes, the code is ok. The only difference between this line and one above it, is that it doesn’t have (or however its called) parameter

It needs the uspotlightcomponent class passed in the angular brackets

Wait, what? Yes, it worked, but HOW? When I asked this question, the code was just the same. Is it some bug?