Value initialization in C++

Value initialization in C++

In Value initialization the initializer is an empty pair of parenthesis.
This is the major feature release in C++3.0

  • If user has default Constructor – it calls constructor
  • else, you get zero initialization.
    example:

 

Case 1: Zero initialization


int main()
{
   return int();  // value initialization
}
 

 

Case 2: No user defined constructor i.e. no user defined initialization.


struct Foo
{
	int i;
}

Foo get_foo()
{
	return Foo();
}
int main()
{
   return get_foo().i;  //return 0.
}

 

Case 3: With User defined constructor


struct Foo
{
	Foo() {}  // constructor defined
	int i;
}
Foo get_foo() 
{
	return Foo();
}
int main()

{
   return get_foo().i;  //Undefined behavior.
}

Solution: defined constructor as default, which will return zero, as default signifies no user defined initialization.
Foo() = default;

 

Case 4: default constructor outside class, it will be treated as user provided.


struct Foo
{
	int i;
}
Foo::Foo()=default; // constructor defined
Foo get_foo() {
	return Foo();
}
int main()
{
   return get_foo().i;  //Undefined behavior.
}