2

I've always run with the assumption that all primitives I allocate, initially contain either whatever that address contained previously (garbage) or they contain a debug pattern of bits.

However, I read offhand somewhere, that a constructor will zero out any members that "it cannot reach" in the constructor. I wish I remember where I read that, because it's bugging me a lot now.

My question is, is there a circumstance where certain members of an object are initialized to zero on construction?

Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • 1
    Only members that have their own constructors will be initialized. – Galik Feb 23 '15 at 01:17
  • http://stackoverflow.com/questions/2614809/what-is-the-default-value-for-c-class-members check this, It kind of answer your question – user116541 Feb 23 '15 at 01:22
  • I don't know what "cannot reach" means, but basic data types such as ints are NOT implicitly initialized to zero by constructors. – Neil Kirk Feb 23 '15 at 01:48
  • @NeilKirk - I can only guess I'm remembering what I read incorrectly then. I still can't find it, but at least I know it's not the case now. – Anne Quinn Feb 23 '15 at 01:55
  • @Galik, that's not quite true. Unless otherwise explicitly stated by the constructor of your class, the default constructor of every member variable gets called. The default constructor for primitives is just like the default constructor for any other class that is automatically generated by the compiler. They don't do anything other than calling default constructor of member variables and parent classes. Primitives don't have member variables or parents, so their default constructors don't do anything. Note that this is different from value-initialization. – thang Feb 23 '15 at 02:19
  • 1
    Worth noting that when you get garbage, it's your own garbage, not someone else's... that would be a security breach. In a system with virtual memory as the heap and a thread's stack grows the O/S will allocate pages that are all zero. Once you free something on the heap and reuse that memory or the stack retraces to a previously visited memory you get your own garbage - http://stackoverflow.com/questions/6004816/kernel-zeroes-memory – amdn Feb 23 '15 at 02:34

1 Answers1

2

As Galik stated, only objects will get initialized (with the default constructor). Some compilers initialize primatives, but you would be writing fundamentally incorrect code if you took advantage of this "feature".

Yoshiya
  • 452
  • 5
  • 17