Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Why the members are not default initialized?

If I have a struct Foo and a struct Bar:

struct Foo {
  int a, b;
};

struct Bar {
  Foo foo;  
  int c;
};

If I initialize a Bar and print the values I correctly get:

int main() {
  Bar bar = {}; // I call the default constructor
  std::cout << bar.foo.a << " "; // 0
  std::cout << bar.foo.b << " "; // 0
  std::cout << bar.c << std::endl; // 0

  return 0;
}

But now if I declare a constructor like this:

struct Bar {
  Bar() : c(5) {}

  Foo foo;  
  int c;
};

I lose the default construction of Bar::foo and the program outputs 32764 0 5!

Why am I forced to dumbly initialize every member variable like this:

struct Bar {
  Bar() : c(5) {}

  Foo foo{};  
  int c;
};

as long as I declare a constructor? Why doesn't the default construction works in this case?

like image 904
Jojolatino Avatar asked Dec 07 '25 03:12

Jojolatino


1 Answers

In C++, if you have a default constructor, and the variables aren't initialized with the initializer list, then it default constructs to an indeterminate value. This is a noted behaviour which hasn't been fixed, so I assume it's either intended, or more likely accepted.

From CPP Reference:

Notes

Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values (static and thread-local objects get zero initialized)

References and const scalar objects cannot be default-initialized.

like image 55
Gabe Ron Avatar answered Dec 08 '25 17:12

Gabe Ron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!