Home > OS >  Why does default constructor only work with class pointers?
Why does default constructor only work with class pointers?

Time:08-21

I've been messing around with a default constructor example inspired by Screenshot

CodePudding user response:

It's because x is uninitialized. Reading uninitialized variables makes your program have undefined behavior which means it could stop "working" any day. It may also do something odd under the hood that you don't realize while you think everything is fine.

These all zero-initialize x:

Foo* b = new Foo();
Foo* b = new Foo{};
Foo b{};

while these don't:

Foo *b = new Foo;
Foo b;

MSVC may not catch and warn about all cases where you leave a variable uninitialized and read it later. It's not required to do so - which is why you may get the warning in one case but not the other.

  • Related