Consider this code:
class First
{
public:
int y;
First()
{
y = 90;
}
};
class Second{
public:
int x;
First ob; //if i comment it, value of x is initialised to zero
};
int main()
{
Second obj = Second();
cout << obj.x << endl;
}
This program gives different output when I change it:
- If I comment out the line
First ob;then value of x is initialised to zero - If the class consists object of class First, then member has garbage value.
- If I create object like
Second obj;then it has garbage value.
What is the reason it behaves differently when Second class consists only built-in members and when object of another class?
And what is the difference between these statements:
Second obj = Second();
Second obj;
Case 1. When you comment out the line
First ob, thenSecondclass becomes a POD type, which can be value-initialized using the syntaxSecond obj= Second(), and value-initialization, in case of built-in types, means zero-initialized, soxis zero-initialized.Case 2: When you keep the line
First ob, thenSecondclass becomes non-POD type, becauseFirstclass is non-POD type (as it has user-defined constructor1]). In this case, the syntaxSecond obj=Second()doesn’t initialize built-in data type, if you don’t initialize it in the constructor.Case 3: When write
Second obj, then there are again two cases (read them carefully):objwill be default constructed if there isFirst obline. And in this case,xwill not be initialized at all, as it is not manually initialized in the constructor ofSecond.objwill not be initialized at all if youFirst obline is commented out. In this case,Secondbecomes a POD, and POD types are not initialized if you only writeSecond obj.1 See this related topic: