ontherocks
ontherocks

Reputation: 1959

Initialize static member array to zero

Going by the document here http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2011/n3242.pdf

“Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place”

If I have everything, i.e class declaration and main() in a single file (a must) I should be able to omit the initialization. But, if I omit, I get "undefined reference" error during build.

#include <iostream>
using namespace std;

class foo
{
    public:
        static int array[2];
};

int foo::array[2] = {0}; //I should be able to omit this line

int main()
{
    cout << "foo::array[0] = " << foo::array[0] << endl;
    return 0;
}

PS: No C++11

Upvotes: 2

Views: 2502

Answers (2)

Ram
Ram

Reputation: 1115

For a static data member of a class, one must compulsorily provide definition in the implementation file because,

static data has a single piece of storage regardless of how many objects are created, that storage must be defined in a single place. The compiler will not allocate storage for you. The linker will report an error if a static data member is declared but not defined.

Upvotes: 0

Daniel Frey
Daniel Frey

Reputation: 56863

I think you are misreading the standard. You can simply drop the = {0} part as the compiler will automatically initialize it with zeros.

You can not leave out the entire line because otherwise you just declare the array but you never define it anywhere - that's what is causing the problem for you.

Upvotes: 8

Related Questions