So I'm currently reading through "The C++ Programming Language" by Bjarne Stroustrup (great book), and it mentions in section 17.3.1 that an object without a defined constructor and that is initialized without an initializer, will (in non-static cases) leave built-in types undefined.
I have this code
#include <iostream>
class A {
public:
int id;
// No constructor defined,
// so default constructor generated
};
void f() {
A a; // No initializer
std::cout << a.id << std::endl;
}
int main(int argc, char *argv[]) {
f();
return 0;
}
I would expect garbage to be printed when I run this code, but instead I get an initialized (0
) value for a.id
. Additionally, if we redefine A
to be:
class A {
public:
int id;
A()=default;
};
Now when I run this code, a.id
will be garbage values, as I had expected previously.
For the first case, why is the id
member of A being initialized? Why are the two cases resulting in different results?
I am using g++/gcc version 8.1.0