Initialization in C++ is bonkers (2017)
Published on: 2025-07-06 23:27:10
C++ pop quiz time: what are the values of a.a and b.b on the last line in main of this program?
#include struct foo { foo () = default ; int a ; }; struct bar { bar (); int b ; }; bar :: bar () = default ; int main () { foo a {}; bar b {}; std :: cout << a . a << ' ' << b . b ; }
The answer is that a.a is 0 and b.b is indeterminate, so reading it is undefined behaviour. Why? Because initialization in C++ is bonkers.
Default-, value-, and zero-initialization
Before we get into the details which cause this, I’ll introduce the concepts of default-, value- and zero-initialization. Feel free to skip this section if you’re already familiar with these.
T global ; //zero-initialization, then default-initialization void foo () { T i ; //default-initialization T j {}; //value-initialization (C++11) T k = T (); //value-initialization T l = T {}; //value-initialization (C++11) T m (); //function-declaration new T ; //default-initialization new T (); //value-initialization new T {};
... Read full article.