-1
#include <iostream>

class X {
    public:
    int a;

};
int main(int argc, char *argv[]) {

    X x;
    std::cout<<x.a<<std::endl;

  }

why is 2130567168? not 0?

jiafu
  • 6,338
  • 12
  • 49
  • 73
  • 4
    "Luck" - because if it was 0 here, you might have relied upon it! – user2246674 May 07 '13 at 04:00
  • 1
    Well, what do you expect it to be? –  May 07 '13 at 04:06
  • 3
    I'm guessing the OP had some experience with Java, where integer _fields_ are initialized to 0, in which case, a good answer might be "because C++ is different from Java" #justsayin – Ray Toal May 07 '13 at 04:11

1 Answers1

8

It could be anything. Since x.a is uninitialized it's value is Indeterminate.
In C++, class members are not default initialized. They need explicit initialization, in the absence of any they remain uninitialized. Using any such uninitialized class members gives your program only one thing, Undefined Behavior.

You need to initialize x.a to something meaningful, using the Member Initializer list.

class X 
{
    public:
        int a;
         X(int i):a(i){}
         X():a(0){}
};
Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533