Does the class constructor need to initialize a non-static bool type field to false or is it guaranteed to be done for me?
5 answers
Need to. That is how, there will be an incomprehensible meaning. And just in case, to know exactly what is false there. Always when declaring variable it is desirable to initialize it.
Correctly it is done like this:
class foo { bool bar; public: foo():bar(false) { }; }; Initialization inside the initialization list - the most correct approach to initialization!
@Ivan in fact, in the case of primitive types there is no particular difference. But if the type is composite - initialization will occur twice - the constructor will be called first by default, and then assignment will occur.
In order not to waste system resources, it is necessary to develop a habit - everything that can be placed on the initialization list should be there.
- Why? What is the difference if I write
bar = false;in the body offoo()bar = false;? - Ivan
Need to. Nobody will do anything for you. The field will be simply uninitialized.
In general, I advise you to feel everything yourself. After all, this is how new things and laws become understandable and elementary.
- @VladD understood what you are driving at But still leave the last paragraph - dirkgntly
C ++ is needed, otherwise there will be rare bugs.
C # is not, there it is automatically done.
Yes, it is necessary to initialize the class / structure fields in his / her constructor.
This class / structure field will not be initialized (that is, the field will take a random value of that area of the stack / heap (depending on how you create an instance of your class / structure) that the compiler allocated for an instance of your class / structure.
It is also worth noting that in the absence of any constructor in most compilers, the class / structure fields will be initialized to 0x00 .
Explicit and implicit variable initialization
If the definition of a variable does not explicitly assign any value to it (that is, it does not explicitly initialize ), then the compiler can initialize it itself in accordance with the following rules:
- variables with static lifetime (global, in namespaces and static) are initialized to zero
- automatic variables are not initialized (i.e., they have a random value of the stack area that the compiler allocated for the variable)
- dynamical variables are not initialized (i.e. have a random value of the memory area that was allocated for an object in the heap)
It is worth noting that in most of the implementations in the debug version for automatic variables, the stack area is filled with 0xCCCCCCCC values, and the heap area is filled with 0xCDCDCDCD , which may allow detecting the use of uninitialized variables during debugging.