Does a c++ struct have a default constructor?

The simple answer is yes.
It has a default constructor.

Note: struct and class are identical (apart from the default state of the accesses specifiers).

But whether it initializes the members will depends on how the actual object is declared. In your example no the member is not initialized and a has indeterminate value.

void func()
{
    _bar_  a;                 // Members are NOT initialized.
    _bar_  b = _bar_();       // Members are zero-initialized
    // From C++14
    _bar_  c{};               // New Brace initializer (Members are zero-initialized)


    _bar_* aP = new _bar_;    // Members are NOT initialized.
    _bar_* bP = new _bar_();  // Members are zero-initialized
    // From C++14
    _bar_  cP = new _bar_{};  // New Brace initializer (Members are zero-initialized)
}

// static storage duration objects
//   i.e. objects at the global scope.
_bar_ c; // Members are zero-initialized.

The exact details are explained in the standard at 8.5 Initializers [dcl.init] paragraphs 4-10. But the following is a simplistic summary for this situation.

A structure without a user defined constructor has a compiler generated constructor. But what it does depends on how it is used and it will either default initialize its members (which for POD types is usually nothing) or it may zero initialize its members (which for POD usually means set its members to zero).

PS. Don’t use a _ as the first character in a type name. You will bump into problems.

Leave a Comment