1

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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
That Guy
  • 43
  • 1
  • 3

2 Answers2

5

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) {}
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

Unless you explicitly use a "in class initializer" - like int member = 0; or add a constructor that initializes the member, then its value will be undefined.

It will not (necessarily) be whatever is stored at the memory address at runtime. It is undefined; meaning you cannot use it reliably and if you do, your compiler may take advantage of the fact that you are then invoking "undefined behaviour" and may optimize your program based on that fact - something you most certainly do not want.

Always initialize your variables before use.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70