I can not find unambiguous information on the topic of resetting the class fields in the constructor. The notions of ΡΡΠΈΠ²ΠΈΠ°Π»ΡΠ½ΡΠΉ and Π½Π΅ΡΡΠΈΠ²ΠΈΠ°Π»ΡΠ½ΡΠΉ ΡΡΠΈΠ²ΠΈΠ°Π»ΡΠ½ΡΠΉ especially confusing.
Suppose we have a class:
class Object { int i; Type t; }; When can i and t remain uninitialized after constructing an object of class Object ?
Someone says that if a constructor is not explicitly described for Object , then the compiler will generate an implicit default constructor that will call the default constructors for each field. In this case, the default constructors will be called for the fields i and t . i will be 0.
However, if we define our constructor in which we do not explicitly call the constructors of the fields i and t , then when we call this constructor, the behavior will be unusual:
iwill remain uninitialized;tinitialized by the default constructort::t().
I am completely confused:
class Type { public: Type() : value{0} {} int value; }; class Trivial { public: int i; Type t; }; class NotTrivial { public: NotTrivial(){} int i; Type t; }; void main() { Trivial trivial; // ΠΠΎΠ»Π΅ i ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½ΠΎ 0. // ΠΠΎΠ»Π΅ t ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½ΠΎ. NotTrivial notTrivial; // ΠΠΎΠ»Π΅ i Π½Π΅ ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½ΠΎ. // ΠΠΎΠ»Π΅ t ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½ΠΎ. }
iremains uninitialized in both cases. Becauseintis a type with a trivial constructor. In addition, theTrivialclass actually has a non-trivial constructor, likeNotTrivial. Well, there is also a fundamental error - by the value stored in the variable, it is impossible to judge whether this variable was initialized or not. - VTTstd::is_trivially_constructible- VTT