Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is default initializing class members always advisable?

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.

like image 654
Anubis Avatar asked Dec 10 '22 00:12

Anubis


1 Answers

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.

like image 175
Mark Ransom Avatar answered Dec 23 '22 07:12

Mark Ransom