Lesson 109 +10 XP

Default Member Initialization

Default Member Initialization

An int member that never receives a value is unpredictable. Default member initializers give members a safe starting value, applied whenever nothing else provides one.

The garbage problem

struct Person {
  string name;
  int age;
};

Person p;   // p.age holds garbage until you set it

Reading p.age now is a mistake, because the member was never initialized.

Fix it with an equals sign

struct Person {
  string name = "unknown";
  int age = 0;
};

Person p;   // name = "unknown", age = 0

The value after = is the default member initializer (DMI).

The empty-brace form

You may also write the member with empty braces, meaning "the zero value of this type":

struct Player {
  int score {};
  string name {};
  double ratio = 1.5;
};

Player pl;   // score = 0, name = "", ratio = 1.5

How the default applies

The default kicks in only when the member gets no value from an expression:

struct Person {
  string name = "unknown";
  int age = 0;
};

Person p { 30 };          // name = "unknown", age = 30
Person q { "Bob", 80 };   // name = "Bob", age = 80

Here aggregate. If a value appears, it wins; otherwise the default steps up.

Why this is good

  • No more reading garbage from a brand-new object.
  • Objects start out correct without extra code.
  • You can create an object and only override the pieces that matter.

TL;DR

  • Default member initializers: int age = 0; or int age {}; inside the struct.
  • {} means the zero value; = value sets an explicit default.
  • The default is used when nothing else supplies a member.
  • Without a default initializer, an int member stays uninitialized.
  • Defaults make creating new objects safe and short.