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.

7
  • 1
    Also stackoverflow.com/questions/41219291/… and a few more questions. Commented Apr 19, 2019 at 8:41
  • I'm asking about the specific case where it's explicitly defaulted, not the case where it's not provided at all. Commented Apr 19, 2019 at 8:43
  • The question you linked doesn't provide an answer regarding differences in the initialization of primitives that are member variables Commented Apr 19, 2019 at 8: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 Commented Apr 19, 2019 at 8:55
  • 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. Commented Apr 19, 2019 at 9:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.