I want to have a struct without default constructor. The reasoning is that the struct only makes sence with a parameter so i want to force to apply it. I ideally would not want to use an UObject because this class is similar to FVector or FTransform so having a struct makes it easier to handle then UObject.
Something like this would be nice:
USTRUCT()
struct FBar {
GENERATED_BODY()
UPROPERTY()
UFoo* Foo;
// some other properties
FBar(UFoo* foo) {
Foo = foo;
}
// functions doing calculations using foo
};
But sadly unreal wont allow not defining a default constructor
That is correct, you must be able to default construct your object.
For example, when demarshaling this value from an archive, the engine must first create an empty instance (before it knows what data goes in it) and then it un-archives into the struct.
Also, structs are often used without pointer references – you can have a flat array of structs. What would you do when you resize such an array, if you couldn’t default construct the instances?
If you will only ever use something as a reference (through a pointer) make it an UObject.
thx for the answer. I dont really want to have an UObject because then i have to take care of destroying it. The struct is only there to simplify some code.
I have a DataAsset that defines a grid dimensions. Then i want to do math based on that so i created structs FGridCell and FGridTransform to easily do calculations. But FGridCell never makes sence without a the grid dimensions and im only using it at runtime. Would have loved to only be able to use FGridCell(foo) and not allow default construction because then i dont have to handle it in another way (Since there are also no exceptions in cpp)
when you dont have a constructor it uses a default constructor. Creating one with parameter will disable that one and you have to create the default constructor manually. It gives an error when you dont do that. But i wanted to specifically not have a default constructor for my usecase
FBar; // i wanted an error here
FBar(something); // only this should work
No you don’t. That’s the whole point of the Unreal header tool and reflection system – UObjects are automatically garbage collected.
To make sure it happens sooner rather than later, you can use a TObjectPtr<YourClass> to improve behavior, but even just a plain UPROPERTY() that is a UObject* subclass pointer will run garbage collection in the end.
Yes, UObjects also need to be able to be constructed through the archive system.
Because Unreal reflection supports save/restore both in level editor, and for game saves, and for networking, you can’t use an object that can’t be default-constructed with the Unreal reflection system.
You can use such objects without making them USTRUCT() and not having any UPROPERTY(), of course! And maybe that’s good enough for your use case. But, all the nice editor/network/savegame integration we all like in the editor, requires default constructed objects by necessity.