views:

268

answers:

4

If I have a

class A
{
private:
  Widget* widgets[5];
};

Is it guaranteed that all pointers are NULL, or do I need to initialize them in the constructor? Is it true for all compilers?

Thanks.

+3  A: 

The array is not initialized unless you do it. The standard does not require the array to be initialized.

Richard Pennington
A: 

It depends on the platform and how you allocate or declare instances of A. If it's on the stack or heap, you need to explicitly initialize it. If it's with placement new and a custom allocator that initializes memory to zero or you declare an instance at file scope AND the platform has the null pointer constant be bitwise zero, you don't. Otherwise, you should.

EDIT: I suppose I should have stated the obvious which was "don't assume that this happens".

Although in reality the answer is "it depends on the platform". The standard only tells you what happens when you initialize explicitly or at file scope. Otherwise, it is easiest to assume that you are in an environment that will do the exact opposite of what you want it to do.

And if you really need to know (for educational or optimizational purposes), consult the documentation and figure out what you can rely on for that platform.

MSN
So its guranteed to be NULL if you do the extra work. In otherwords no they are not NULL in all normal situations.
Martin York
Yes. I would phrase it as it's not necessarily NULL, or rather, it's never guaranteed to be NULL, but it may happen to be NULL. Whee!
MSN
+2  A: 

It is not initialized if it is on the stack or using the default heap allocator (although you can write your own to do so).

If it is a global variable it is zero filled.

This is true for all conformant compilers.

Terry Mahaffey
A: 

In general case the array will not be initialized. However, keep in mind that the initial value of the object of class type depends not only on how the class itself is defined (constructor, etc), but might also depend on the initializer used when creating the object.

So, in some particular cases the answer to your question might depend on the initializer you supply when creating the object and on the version of C++ language your compiler implements.

If you supply no initializer, the array will contain garbage.

A* pa = new A;
// Garbage in the array

A a;
// Garbage in the array

If supply the () initializer, in C++98 the array will still contain garbage. In C++03 however the object will be value-initialized and the array will contain null-pointers

A* pa = new A();
// Null-pointers in the array in C++03, still garbage in C++98

A a = A();
// Null-pointers in the array in C++03, still garbage in C++98

Also, objects with static storage duration are always zero-initialized before any other initialization takes place. So, if you define an object of A class with static storage duration, the array will initially contain null-pointers.

AndreyT