Search code examples
c++c++11initializationlanguage-lawyerdefault-constructor

Is it guaranteed that defaulted constructor initialize built in types automatically to 0?


Before you start to mark this as duplicate I've already read this .But It doesn't answer my question. The linked question talks about C++98 & C++03 but my question is about defaulted constructor introduced by C++11.

Consider following program (See live demo here):

#include <iostream>
struct Test
{
    int s;
    float m;
    Test(int a,float b) : s(a),m(b)
    { }
    Test()=default;
}t;
int main()
{
    std::cout<<t.s<<'\n';
    std::cout<<t.m<<'\n';
}

My question is that is the defaulted constructor provided by compiler here always initializes built in types to by default 0 in C++11 & C++14 when they are class & struct members. Is this behavior guaranteed by C++11 standard?


Solution

  • Test = default will default initialize its members. but for type as int or float, default initialization is different than value-initialization

    so

    Test t; // t.s and t.m have unitialized value
    

    whereas

    Test t{}; // t.s == 0 and t.m == 0.0f;