That Guy That Guy - 1 year ago 69
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
to a default vlaue unless explicitly stated in a user defined constructor, correct? So that this:

MyStruct object;

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
when I create an object of
or is
left uninitialized?

Answer Source

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) {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download