0

If I have a class:

class MyClass {
   public:
    int value;
};

It's member value won't be zero-initialized if I don't zero-initialize the class:

MyClass c;
std::cout << c.value; // UB: value not initialized.

Does defaulting the default constructor guarantee that members are zero-initialized?

class MyClass {
   public:
    int value;
    MyClass() = default;
};

If I explicitly default the default constructor, will value be initialized to zero now?

MyClass c;
std::cout << c.value; // Guaranteed to print zero?

Note: This question is not a duplicate because I'm asking about the case where the default constructor is explicitly defaulted, and the other question just covers the case where it's not provided.

Alecto Irene Perez
  • 10,321
  • 23
  • 46
  • 1
    Also https://stackoverflow.com/questions/41219291/defaulted-constructor-vs-implicit-constructor and a few more questions. – MSalters Apr 19 '19 at 08:41
  • I'm asking about the specific case where it's explicitly defaulted, not the case where it's not provided at all. – Alecto Irene Perez Apr 19 '19 at 08:43
  • The question you linked doesn't provide an answer regarding differences in the initialization of primitives that are member variables – Alecto Irene Perez Apr 19 '19 at 08:44
  • AFAIK, on GCC it will generate you a warning `'c.MyClass::value' is used uninitialized in this function [-Wuninitialized]` and print 0, but Clang won't issue you a warning, and will print 0. I'm talking about the latest Clang 9.0.1 and Gcc 9.0.1 – mutantkeyboard Apr 19 '19 at 08:55
  • The first comment answers the "how is explicitly defaulted different" part - it's identical with regard to member initialization. The difference is in access control. – MSalters Apr 19 '19 at 08:55
  • Thank you - sorry about that – Alecto Irene Perez Apr 19 '19 at 08:59
  • 2
    @mutantkeyboard: That's the problem with Undefined Behavior - it may give results that **look** reliable. Visual Studio in debug builds probably will not give 0, as it intentionally writes non-zero patterns prior to initialization. – MSalters Apr 19 '19 at 09:18

0 Answers0