C++ pop quiz time: what are the values of a.a and b.b on the last line in main of this program? #include <iostream> 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{}; //value-initialization (C++11) } struct A { T t; A() : t() {} }; //t is value-initialized struct B { T t; B() : t{} {} }; //t is value-initialized (C++11) struct C { T t; C() {} }; //t is default-initialized The rules for these different initialization forms are fairly complex, so I’ll give a simplified outline of the C++11 rules (C++14 even changed some of them, so those value-initialization forms can be aggregate initialization). If you want to understand all the details of these forms, check out the relevant cppreference.com articles, or see the standards quotes at the bottom of the article. default-initialization – If T is a class, the default constructor is called; if it’s an array, each element is default-initialized; otherwise, no initialization is done, resulting in indeterminate values. value-initialization – If T is a class, the object is default-initialized (after being zero-initialized if T’s default constructor is not user-provided/deleted); if it’s an array, each element is value-initialized; otherwise, ...
First seen: 2025-05-15 22:41
Last seen: 2025-05-16 13:43