# Initialize components in C++ the correct way

**URL:** <https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946>\
**Category:** Programming & Scripting\
**Tags:** unreal-engine\
**Created:** [May 5, 2022, 10:11pm UTC](https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946 "2022-05-05T22:11:52Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![rubm123](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/rubm123/32/476292_2.png) [@rubm123](https://forums.unrealengine.com/u/rubm123)\
**Post date:** [May 5, 2022, 10:11pm UTC](https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946/1 "2022-05-05T22:11:52Z")

</div>

Is this following piece of code correct:

```auto
// some .h file

class AMyCustomActor : public AActor
{
    GENERATED_BODY()

public:
    AMyCustomActor::AMyCustomActor()
    {
        Root = CreateDefaultSubobject<USceneComponent>(TEXT("SceneRoot"));
	    SetRootComponent(Root);
  
        SomeStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SomeStaticMesh"));
        SomeStaticMesh->SetupAttachment(Root);
        
        SomeActorComponent = CreateDefaultSubObject<UActorComponent>(TEXT("SomeActorComponent"));
        SomeActorComponent->RegisterComponent();
    };

protected:
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    TObjectPtr<USceneComponent> Root;

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    TObjectPtr<UStaticMeshComponent> SomeStaticMesh;

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    TObjectPtr<UActorComponent> SomeActorComponent;

    // ...

```

- Is `SetupAttachment` necessary and sufficient for any scene component?
- Is `RegisterComponent` necessary and sufficient for any none-scene component?

Thanks

---

<div class="post-metadata">

**Author:** ![rubm123](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/rubm123/32/476292_2.png) [@rubm123](https://forums.unrealengine.com/u/rubm123)\
**Post date:** [May 5, 2022, 10:17pm UTC](https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946/2 "2022-05-05T22:17:08Z")

</div>

And for bonus points:

- Is `RegisterComponent` always redundant after `SetupAttachment` (for scene components)?
- What does `AddInstanceComponent` add to the mix?

---

<div class="post-metadata">

**Author:** ![KaidoomDev](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/kaidoomdev/32/977996_2.png) [@KaidoomDev](https://forums.unrealengine.com/u/KaidoomDev)\
**Post date:** [May 6, 2022, 1:52am UTC](https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946/3 "2022-05-06T01:52:14Z")

</div>

I usually open up classes like Character.cpp and see how they created the character movement component etc.

No need to call RegisterComponent in constructor, this is only needed when creating the component dynamically at runtime, for example at begin play or after an even occurs in game.

Setup attachment is also preferred in constructor, however at runtime you’d use attach component to component.

---

<div class="post-metadata">

**Author:** ![rubm123](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/rubm123/32/476292_2.png) [@rubm123](https://forums.unrealengine.com/u/rubm123)\
**Post date:** [May 6, 2022, 2:27pm UTC](https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946/4 "2022-05-06T14:27:15Z")

</div>

Thanks for the hint. Indeed, I can check out existing code to get a more definite idea.

I have read that `RegisterComponent` is not needed in the constructor. But does that mean that actor components don’t need any further step? They will show up in the editor anyway?

Also, using `SetupAttachment` when creating components at runtime does work for me, too, in which case `RegisterComponent` seems to be redundant there, too. So I am still not sure, what I am doing really and just trying out to see what works.

---

<div class="post-metadata">

**Author:** ![rubm123](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/rubm123/32/476292_2.png) [@rubm123](https://forums.unrealengine.com/u/rubm123)\
**Post date:** [May 6, 2022, 3:33pm UTC](https://forums.unrealengine.com/t/initialize-components-in-c-the-correct-way/549946/5 "2022-05-06T15:33:59Z")

</div>

Testing after taking in account @KaidoomDev 's advice results in this correct code for defining components in C++ at build time:

```auto
// some .h file

class AMyCustomActor : public AActor
{
    GENERATED_BODY()

public:
    AMyCustomActor::AMyCustomActor()
    {
        Root = CreateDefaultSubobject<USceneComponent>(TEXT("SceneRoot"));
	    SetRootComponent(Root);
  
        SomeStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SomeStaticMesh"));
        SomeStaticMesh->SetupAttachment(Root);
        
        SomeActorComponent = CreateDefaultSubObject<UActorComponent>(TEXT("SomeActorComponent"));
    };

protected:
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    TObjectPtr<USceneComponent> Root;

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    TObjectPtr<UStaticMeshComponent> SomeStaticMesh;

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    TObjectPtr<UActorComponent> SomeActorComponent;

    // ...

```

And at runtime, the following works:

```auto
    // the `FName` needs to be unique, therefore I construct it using the loop index `i`
    const auto SplineMesh = NewObject<USplineMeshComponent>(this, *FString(TEXT("SplineMesh")).Append(FString::FromInt(i)));
    // if I don't register here, the spline mesh doesn't render
	SplineMesh->RegisterComponent();
	SplineMesh->AttachToComponent(Root, FAttachmentTransformRules::KeepWorldTransform);
	// if I don't add instance here, the spline meshes don't show in the component list in the editor
	AddInstanceComponent(SplineMesh);
		
    // specific set up of spline mesh component
	SplineMesh->SetMobility(EComponentMobility::Stationary);
	SplineMesh->CastShadow = false;
	SplineMesh->SetStaticMesh(SM_Trajectory);
	const auto VecStartPos = Spline->GetLocationAtSplinePoint(Indices[i], ESplineCoordinateSpace::World);
	const auto VecStartDirection = Spline->GetTangentAtSplinePoint(Indices[i], ESplineCoordinateSpace::World);
	const auto VecEndPos = Spline->GetLocationAtSplinePoint(Indices[i + 1], ESplineCoordinateSpace::World);
	const auto VecEndDirection = Spline->GetTangentAtSplinePoint(Indices[i + 1], ESplineCoordinateSpace::World);
	SplineMesh->SetStartAndEnd(VecStartPos, VecStartDirection, VecEndPos, VecEndDirection);
```
