Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor initialization of built-in types

Tags:

c++

gcc

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

like image 680
Julian Mendoza Avatar asked Feb 02 '26 00:02

Julian Mendoza


1 Answers

but instead I get an initialized (0) value for a.id

Just because the value happens to be 0 doesn't mean it's initialized. Reading an uninitialized value is undefined behavior so the output can be anything, including 0.

If I run this same code on my system, I get the following output:

791621423
like image 88
dbush Avatar answered Feb 04 '26 14:02

dbush