Search code examples
c++default-constructor

Compiler generated default constructor working - C++


I am trying to learn about the default constructor working of class and am not able to figure out this situation:

Case 1:

class A  
{  
  public:
     int m;
     string s;
};

Then I create object of this class:
a) A a; // Result: compiler initializing m with garbage value
b) A a = A(); // Result : compiler initializing m with garbage value

Case 2: Now I removed string s from my class:

class A
{
  public:
    int m;
};

a) A a; // Result: when try to access m I get run time error
b) A a = A(); //Result: m is initialized to zero

Q1) Why there is discrepancy in case 1 and case 2?
Q2) What if I provide default constructor to my class in both cases then a) & b) will be same?


Solution

  • Case 1: Class A is a non POD.
    Case 2: Class A is a POD.

    a) A a; //This is default initialization
    b) A a = A(); // This is value initialization
    

    Case '1': m will be initialized to some garbage value by the compiler generated default constructor.

    Case '2': m will be zero initialized because A is a POD.

    You should not be getting a crash in any of the scenarios. If you do probably you are using a broken compiler.

    For more details on default initialization and value initialization refer to this link.