I've been messing around with a default constructor example inspired by this answer. This one works fine:
class Foo {
public:
int x;
Foo() = default;
};
int main() {
for (int i = 0; i < 100; i++) {
Foo* b = new Foo();
std::cout << b->x << std::endl;
}
But when I try this out with a class instance on the stack it does not! For example, if I instantiate the class like Foo b
I get an error saying uninitialised local variable 'b' used.
However, when I change the constructor to Foo() {}
, instantiation with Foo b
works fine, and I see random garbage from b.x
as expected.
Why doesn't a default constructor work when I instantiate a class on the stack?