-5
class test {
public:
    test() {};
    bool active;
};

int main()
{
    test a;

    cout << a.active << endl;

    return 0;
}

The following code always prints 204. I tested many other types, and got some very strange results. An int prints -858993460, a double prints -9.25596e+61 and the list goes on.

Why doesn't C++ throw an error such as uninitialized class member 'active' used instead of assigning what seems to be an arbitrary value?

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
John Landon
  • 2,121
  • 2
  • 12
  • 11
  • 4
    If you want the language to hold your hand like that, don't use C++. – Brian Bi Sep 09 '17 at 20:22
  • 8
    C++ basically follows this principle: *You don't pay for what you don't use.* Not everyone wants or needs exceptions. – Rakete1111 Sep 09 '17 at 20:22
  • @Brian I was more interesting the explanation behind why this happens, the fact that it does doesn't bother me. – John Landon Sep 09 '17 at 20:23
  • 3
    Asking questions like this isn't really sensible - it's the way the language is defined; live with it. But if you want a reason, it's because default initialisation may be expensive, and you may not want it. –  Sep 09 '17 at 20:23
  • @JohnLandon Exceptions are costly. And since C++ was built for speed, it doesn't force you to pay for what you don't need. – Algirdas Preidžius Sep 09 '17 at 20:30
  • _The following code always prints 204_ I don't think that that happens. –  Sep 09 '17 at 22:08

1 Answers1

0

C++ just allocates the memory and calls the constructor. You're free to initialize all members as you wish.

What actually happens while you're compiling in debug mode is that the compiler actually does initialize the different members to certain values that would help you understand it's uninitialized.

204 is 0xCC which is the default (microsoft?) debugger initialization value

A similar question and nice answers here: What happens to a declared, uninitialized variable in C? Does it have a value?

Gabi Lee
  • 1,193
  • 8
  • 13