It's general advice to avoid getting uninitialized members in a class/struct. Consider the following example.
struct Foo
{
Foo(){}
int bar;
}
To follow the advice, I have to explicitly initialize bar (e.g. int bar{};
).
But what if I always initialize the member by assigning a value to it right after construction (let's forget passing an assigned value as a constructor argument). Should I still follow the above recommendation here? I would still do it if there is no overhead. But, even though negligible, there has to be an associated runtime overhead due to the unused first initialization.
Initializing member variables leads to more stable and predictable class operation; there's no possibility of having the object in an unknown or inconsistent state. On the other hand, certain operations can be relatively slow, and if you know your program logic won't leave the members uninitialized for long you can certainly get away with leaving them. In C, there's no constructor to fill in those members but people have been programming successfully in C since forever.
The cost of initializing an int
isn't enough to be worth worrying about 99.9% of the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With