C++ tip: use default initialiazation for "unspecified"/"I-don't-care" values

[In this particular lesson, this is regarding the DamageType parameter in FPointDamageEvent]

When you don’t care about the value of a parameter/variable, or want to leave it unspecified, in C++ you should not use specific values like 0, nullptr, …, you should use {} instead.

{} is more expressive of “unspecified” than specific values. “I-want-nullptr” is not necessarily the same as “unspecified”.
This distinction is also why Unreal has TOptional and C++ has std::optional.

For basic types, {} becomes 0, false, nullptr, …, as one would expect.
For classes, it will call the default constructor (*), which may do things differently (see TOptional/std::optional) and potentially more optimized, than a constructor with a specific value parameter.

So for this particular Unreal lesson, the code would be better if it was:

FPointDamageEvent DamageEvent(Damage, Hit, ShotDirection, {});

with that last parameter being {} instead of nullptr.
In this case, this is equivalent too, since internally, TSubClassOf<T>'s default constructor will initialize itself with nullptr.

(*) If the class doesn’t have a default constructor, then of course you’ll have to specify the value (and in which case, make double sure that nullptr is acceptable, because that’s probably the reason why there isn’t a default constructor to begin with)

3 Likes

Privacy & Terms