Default Initialization in C++

Default Initialization in C++

Default Initialization is the initialization performed when an object is constructed with no initializer.

Default initialization occurs in three scenarios:
1) when a variable with automatic, static, or thread-local storage duration is declared with no initializer;

2) when a new-expression with no initializer creates an object with dynamic storage duration;

3) When a base class or a non-static data member is not specified in a constructor  initializer list and that constructor  is called.

In C program:

Since variable are not initialized at the time of declaration, hence result will be undefined behavior.

int main()
{
   int i;
   return i;  //undefined behavior
}

struct Foo{
	int i;
	int j;
}
int main()
{
	Foo foo;
	return foo.i;  //undefined behavior
}

In C++ Program:

Even in C++ this will be an undefined behavior since data members are not initialized.

class Foo {
   public:
 
  Foo() {}
   

   int get_i()  const noexcept { return i; }
   int get_j()  const noexcept { return j; }
   
   private:
	int i;  
	int j; 
};

int main()
{
	Foo foo;
	return foo.get_i();    //undefined behavior.
}

Solution in C++ 98 using member initializer list

class Foo {
   public:
   
   //solution in C++ 98 using member initializer list
   Foo() :i(0), j(0) {}
   int get_i()  const noexcept { return i; }
   int get_j()  const noexcept { return j; }
   
   private:
	int i;    
	int j;    
};

int main()
{
	Foo foo;
	return foo.get_i();    // i=0, here i will get initialized with 0.
}

Solution in C++ 11

C++ 11 provides an option to default member initializer as shown below.

class Foo {
   public:
   
   int get_i()  const noexcept { return i; }
   int get_j()  const noexcept { return j; }
   
   private:
	int i=0;    //default member initializer
	int j=0;    //default member initializer
};

int main()
{
	Foo foo;
	return foo.get_i();    // i=0, here i will get initialized with 0.
}