Why does zero initialization happen even when the base has a constructor declared by the user?

Fingerprint 0 , meaning data , was zero initialization. Why does this happen even if base has a user-declared constructor?

 struct base { base() { } int data; }; struct derived : base { derived() = default; }; int main() { std::cout << derived().data; } 

If derived has a constructor declared by the user, it returns an arbitrary value. Why does zero initialization depend on the derived class, and not on the base class?

+5
source share
1 answer

The rules were specially written to cover

 struct S { int i; std::string s; }; 

where without any user-created constructor, even if the implicitly created constructor is nontrivial by default, S().i will be initialized to zero. This cannot depend on the int constructor, since int has no constructor. It was decided that this would depend on whether the class S has a user-provided constructor. From this there can be no more.

What you see is a simple consequence of this. Your derived class also does not have a constructor provided by the user, so it also gets zero initialization.

+11
source

Source: https://habr.com/ru/post/1210280/


All Articles