4

Why those two scenarios (the initialization of A and of C ) produce different default initialization results in C++ 14? I can't understand the result based on the default initialization rules in cppreference.com

struct A { int m; };
struct C { C() : m(){};  int m; };  

int main() {
  A *a, *d;
  A b;
  A c{};
  a=new A();
  d=new A;
  cout<<a->m<<endl;
  cout<<d->m<<endl;
  cout<<b.m<<endl;
  cout<<c.m<<endl;
  cout<<"--------------------"<<endl;
  C *a1, *d1;
  C b1;
  C c1{};   
  a1=new C();
  d1=new C;
  cout<<a1->m<<endl;
  cout<<d1->m<<endl;
  cout<<b1.m<<endl;
  cout<<c1.m<<endl;
 }

Output:

(Scenario 1)
    0 
    -1771317376
    -1771317376
    0
    --------------------
(Scenario 2)
    0
    0
    0
    0

The post that tries to explain this (but it's not clear to me yet why the difference in the results and what causes m to be initialized in each scenario): Default, value and zero initialization mess

darkThoughts
  • 403
  • 6
  • 18

1 Answers1

-1

A has no user defined constructors, so a default constructor was generated. C has a user defined constructor, so there is no guarantee that a default constructor was generated, especially since the user defined constructor overloads the default constructor. It is almost certain that every construction of C used the user defined constructor.

In the user defined constructor for C uses an initialization list to value initialize C::m. When C::m is initialized, it is value initialized, which includes a zero initialization.

new A; and A b; are default initializations. This does not set assign any values to their members. What value is stored in A::m is undefined behavior.

new A(); and A c{}; are value initializations. As part of the value initialization, it performs a zero initialization.

Johnathan Gross
  • 678
  • 6
  • 19
  • 2
    "C has a user defined constructor, so there is no guarantee that a default constructor was generated". Actually there is a guarantee that the default constructor will not be implicitly generated. – bolov Jul 25 '17 at 07:35