Object created in Constructor points to junk, and crashes on startup

Hey guys,

I’m trying to create a new object in my UObject constructor. I’m calling delete on it in OnComponentDestroyed(bool bDestroyingHierarchy).

In my new objects deconstructor I check to see if it’s pointers are null before trying to delete them. I’m even adding a bool which is false until BeginPlay gets called.

I think whats happening is Unreal has their system that will call the constructor on objects multiple times while a level is loading. These will get garbage collected, and somewhere along the way my new object pointer ends up pointing to something else. How can I avoid this?

UComponent::UComponent(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer)
       bUseComplexAsSimpleCollision = true;

	NewObject = new NewObject();

void UComponent::OnComponentDestroyed(bool bDestroyingHierarchy)
	delete NewObject;

	if (isInitialized)
		if (ptr1 != nullptr)
			delete[] ptr1;
		if (ptr2 != nullptr)
			delete[] ptr2;
		if (ptr3 != nullptr)
			delete[] ptr3 ;

You are on right path sir!!!

Dont create any runtime thing in Constructor, because of UE4’S Reflection system constructor is used little bit different as in native c++ code…
That means Engine will parse class constructors to make classes available for Blueprint, but this parse actually will not create / construct this object really, just reflecting his default data to his child blueprint classes :slight_smile:

Engine has some very good virtual functions which you can override and use them as “Constructors” like OnConstruction, OnPostComponentInitialized, BeginPlay etc… which will run only when object / class is created and initialized fully… you can create objects there safely, but be aware… some of those functions will run in Editor too (when you place your class in the world) :wink:

Thanks for the help! I suppose I should read up on their reflective system more. I’ll look into the OnConstruction function.