How many times does the constructor get called?

Settings changed in the constructor are updated in the derived blueprint with new default values. This should mean that the constructor is getting called before the game.

However, debug messages put in the constructor also successfully show up upon starting the game. They also show up for each instance of that particular class. Does this mean that the constructor gets called multiple times, once for the C++ class and once for each instance of that class? And if it does get called multiple times, is it due to the actor replication stage in the actor lifecycle? Thanks!

1 Like

Constructor is called when object of class is allocated so in case of static on exe start up or in case of dynamic allocation, when new is called, compiler make constructor code to be executed when those action occure, ofcorse aside of explicit costructor call in the code it self. In other words it’s being called every time object is created.

The reason why constructor is called in UE4 in times you don’t expect is because of reflection system. Reflection system stores a not fully imitated master copy of the object containing default state of object called Class Default Object (CDO), from that object UE4 recognizes values of specific properties of class as defaults and knows when property been modified (you probably notice yellow arrows in property editor), it also let save blueprint defaults. There also other potential. Engine created CDO on any module start up (in most cases engine start up) containing perticlar class, as result constructor is called (again this is behavior dictated by C++ compiler not UE4) and by convention UE4 assums that all values set in constructor are default states. There also other possibilities that object may be created for some other reasons executing the constructor even by editor (remember that by coding in UE4 you technicly extending engine as well as editor when you run the project with your module, that why crash caused by your code crash entire editor).

Because of that behavior in UE4 you should not have any game code in constructor (not to mention doing any calles to enigne may cause crash as CDO may be created in early stage of engine initiation), what constructor should only do is set the newly created object to it’s default state and that it. As overcompensate of that UObject class and AActor contain series of different overridabe event functions allowing you to hookup you code on any stage of object or actor initiation and you should use those functions instead of constructor