That Guy That Guy - 18 days ago 6
C++ Question

Struct default constructor: will it initialize my members with default vaues i.e. 'zeros'

I am learning about constructors and I need a clarification. I can build a struct as follows without specifying a constructor:

struct MyStruct {
int member;
}


When I make an object of this struct the generated default constructor will not initialize
member
to a default vlaue unless explicitly stated in a user defined constructor, correct? So that this:

MyStruct object;
cout<<object.member<<endl;


will output some random value depending on what is stored in that memory address at runtime, correct?

My final question is, If I do not explicitly declare and define a constructor will the generated constructor initialize
member
when I create an object of
MyStruct
or is
member
left uninitialized?

Answer

Yes, built-in types are not initialized by the compiler generated constructor.

The compiler generated constructor is exactly the same as:

MyStruct() {}

Accessing MyStruct.member then leads to undefined behaviour. You should explicitly initialize member:

MyStruct() : member(0) {}