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?
Case 1: Class
Ais a non POD.Case 2: Class
Ais a POD.Case ‘1’:
mwill be initialized to some garbage value by the compiler generated default constructor.Case ‘2’:
mwill be zero initialized becauseAis 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.