Reputation: 24067
In my class I was using such field:
private:
bool firstSeqNumReceived;
Everything were working fine for a while but after one commit I've figured out that now field is true
by default. Surprisingly field is not initialized to false
by default, instead assigned value is implementation dependent (refer to What is the default value for C++ class members for more details )
Now I wonder why compiler doesn't produce compile-time error forcing me to add initialization? Who needs "implementation-dependent" default value, are there any use-cases? Why not produce compile-time error in this case?
Upvotes: 0
Views: 323
Reputation: 101484
I wonder why compiler doesn't produce compile-time error forcing me to add initialization?
Because the compiler assumes you know what you're doing.
In C++ you don't pay for what you don't use. There may be use cases where initialization is a waste of time. For example, in a class where real meaningful values for members cannot possibly be computed until after the object has been constructed, initializing the members to some default or sentinel value accomplishes little.
Upvotes: 5
Reputation: 110708
The standard specifies that it is undefined behaviour to access an uninitialized object. There are a few reasons such undefined behaviour appears in the standard. This one is more about not giving you more than you ask for. Sometimes you really don't want to initialize a variable as soon as you create it. Instead, the compiler trusts you to initialize an object when you need it initialized. As an example of when you don't want it initialized automatically:
int x;
std::cin >> x;
It would be completely pointless to automatically initialize x
to 0
as the value is immediately overwritten. The power to initialize a variable is in your capable hands.
Compilers may also assume you do not invoke undefined behaviour in order to make optimizations.
Upvotes: 0
Reputation: 32258
The use-case is basically, that it depends on the program flow if you are using the variable or not. If you don't use it in parts of your code then there is also no need to zero initialise it.
Also if you know, that the value will be assigned in the constructor or some other member function it would be just a superfluous step to first write 0 into memory.
Upvotes: 0