I have been using a lot of UOject classes in my project. Some of them I have found myself not adding any code into the constructor because it doesn’t seem to need any. I know that the class requires a constructor for it to work but apparently there doesn’t need to be code inside for it to compile and for it to run correctly.
What I am wondering is, is this something I should pay attention to? Is it bad coding to not put any code into the constructor?
It’s quite possible you will be in for a quite a shock. Constructors in Unreal Engine don’t work the way they are described in C++. Constructors in Unreal Engine (that have a base class of UObject) are used in CDO (Class Default Object). A Class Default Object defines the default values and components to create a sort of “template” for that class (not to be confused with C++ templates). When you create an instance of that class, it will copy the CDO to the instance to initialize it. This means the constructor is only run for the CDO, not for instances.
Not only that, but CDO has customized functions for certain tasks such as creating a default component. If you want all subclasses to have the same components, you would use the call to CreateDefaultSuboject to create that component. Outside of the constructor, you would use NewObject.
One more thing. In plain C++, you’re likely used to calling the base class constructor from the derived constructor. Like so:
MyClass::MyClass()
: MyBaseClass()
{
}
Don’t do this with classes derived from UObject. Unreal Engine will call all base class constructors automatically.
(edit: It’s actually perfectly fine to call the base class constructor. It’s just no longer necessary.)
To throw a wrench into the mix, there is another constructor that takes an initialization object that can also be used instead of the default constructor. That one CAN call the base class’ constructor since it will pass in the initializer object.
A bit more info here:
If you want to have initialization code like you used to have with plain C++, you can override UObject::PostInitProperties() for that. Don’t forget to call Super::PostInitProperties(). This will be called for each instance. Note that if you don’t have anything differ per instance, best to just stick with the default constructor.
And yes, it’s perfectly fine to leave the constructor empty.
1 Like
Thank you for the awesome response.