0

I have some doubt regarding object creation and memory initialization of an object.

As per below mentioned code, I am getting confused how an object memory is getting initialize by 0, when it is created by using syntax like X a1=X();. Is this syntax wrong? If not,then what is the difference between X a1; and X a1=X();

#include <iostream>
class X
{
public:
        int i;
        int j;
        int k;
        int l;
};

int main()
{
        X a1;
        X a2=X();
        X a3;
#if 1
        std::cout<<a1.i<<":"<<a1.j<<":"<<a1.k<<":"<<a1.l<<std::endl;//Output:369822704:32767:4196976:0  (some garbage value)
        std::cout<<a2.i<<":"<<a2.j<<":"<<a2.k<<":"<<a2.l<<std::endl;//0:0:0:0  (always zero)
        std::cout<<a3.i<<":"<<a3.j<<":"<<a3.k<<":"<<a3.l<<std::endl;//1:32767:0:0 (Always same)
#endif
        return 0;
}
rajenpandit
  • 1,265
  • 1
  • 15
  • 21
  • 2
    The difference is between *default-initialization* and *value-initialization*. The former does *not* initialize the ints, the latter initializes them to zero. – Kerrek SB Oct 22 '15 at 13:39
  • @KerrekSB, Thank you for your comment. After going through the concept of _default-initialization_ and _value-inititalization_ it is clear to me. – rajenpandit Oct 22 '15 at 13:59

0 Answers0