How to write constructor for custom struct

I created a custom struct “FIntVector2D” simply a 2D integer vector using the FIntVector template.

file ObjectLib.h

>     #include "Engine/ObjectLibrary.h"
>     #include "ObjectLib.generated.h"
>     
>     USTRUCT(immutable, noexport, BlueprintType)
>     struct FIntVector2D
>     {
>     	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IntVector2D", SaveGame)
>     		int32 X;
>     
>     	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IntVector2D", SaveGame)
>     		int32 Y;
>     };

That works fine, I can use it the way I want to in Unreal, but I would like to have a constructor such as

FIntVector2d(10, 20);

I have been trying to copy the code from the default FIntVector but can’t for the life of me figure out the exact code thats needed and where to put it.

Hope someone can help or at least point me int eh right direction.

3 Likes

Hello SiberianExpress,

When it comes to doing a constructor for a struct, you can do it just like you would for a normal class. All you need to add is:

 USTRUCT(immutable, noexport, BlueprintType)
 struct FIntVector2D
 {
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IntVector2D", SaveGame)
	int32 X;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IntVector2D", SaveGame)
	int32 Y;

	FIntVector2D();

	FIntVector2D(int32 NewX, int32 NewY)
	{
		 X = NewX;
		 Y = NewY;
	}

 };

Edit: I changed it a bit after noticing that you want to have a constructor that takes values, not one with predefined values. You just need to also make the default constructor or the compiler won’t like it.

Hope this helps!

2 Likes

Just to add to this if you end up here and you’re still getting “no default constructor” or linking errors:

It seems that you always need to set default values of all your struct variables in your constructor. In my case, I did one default constructor with no arguments, initialising all variables to something:

FMyConstructor()
{
     Variable1 = 0;
     Variable2 = nullptr;
     veriable3 = EMyEnum::SomeEnum;
    // etc
}

Then the way I wanted to use it in code:

FMyConstructor(float var1, AActor* var2, TEnumAsByte<MyEnum> var3)
{
    variable1 = var1;
    variable2 = var2;
    variable3 = var3;
}

Finally compiles on my end!

3 Likes