Reputation: 7357
In the struct
struct A
{
int a;
A(){ }
};
A a;
Is it specified which value has a.a
? Doe we have UB if we try to read a.a
?
Upvotes: 0
Views: 85
Reputation: 56547
If A a;
has static storage duration (like defining it outside main()
), or thread storage duration (i.e. defined with thread_local
in C++11 or later), then a
is zero-initialized (thanks @Praetorian for the comment)
3.6.2/2 [basic.start.init] Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.
In your case, this means that each member of your object A a
will be zeroed, hence a.a
will be zeroed, then the constructor A()
will run (which won't do anything). At the end of the day, a.a
will be zero.
If A a
has non-static/non-thread storage duration (e.g. having A a;
inside a function), then no zero initialization is performed, and again the constructor doesn't do anything. So you have UB (undefined behaviour) if you try to read a.a
, since the latter is left un-initialized.
Upvotes: 4
Reputation: 599
If you have used java you might know that variables are assigned a default value in it but that's not the case in c++. Here you only allocate a chunk of memory for your variable. Whatever garbage it contained before it was allocated to you comes with it. So we call it a garbage value. You have to initialize it to your desired value in the constructor of the class or the structure.
Upvotes: 2