How to include CreateDefaultSubobject in C++?

I want to create a wrapper around calls to CreateDefaultSubobject and place it into a header file. The function is defined in Object.h but the code does not compile.

What is the correct way to call this function in a standalone C++ header? The file does not define a class.

#include "CoreMinimal.h"             // ???
#include "UObject/ObjectMacros.h"    // ???
#include "UObject/UObjectGlobals.h"  // ???
#include "UObject/Object.h"          // ???

template <class TReturnType>
TReturnType* GetMinimalComponent(FName SubobjectName, bool bTransient = false)
{
	TReturnType* Component = CreateDefaultSubobject<TReturnType>(SubobjectName, bTransient);

	// Some code here

	return Component;
}

The error is Error : use of undeclared identifier 'CreateDefaultSubobject'

It’s part of UObject so you need to pass the UObject in which you want to call it

#include "CoreMinimal.h"
#include "UObject/Object.h"

template<class TReturnType>
TReturnType* GetMinimalComponent(UObject* Obj, FName SubobjectName, bool bTransient = false)
{
    TReturnType* Component = Obj->CreateDefaultSubobject<TReturnType>(SubobjectName, bTransient);

    // Some code here

    return Component;
}
ASomeActor::ASomeActor()
{
    SomeComp = GetMinimalComponent<USceneComponent>(this, "Foo");
}
1 Like

Of course! Such a basic mistake. Thanks!