Destructor
Destructor

Reputation: 14438

C++: static array inside class having unknown size

I wasn't familiar with this. I searched it on google but didn't find my answer. So, posting my question. Just tried following program:

#include <iostream>
class test
{
    static char a[];
    static int b[];
};
int main()
{
    test t;
}

It compiles fine without any warnings on MSVS 2010 & g++ 4.8.1. It also compiles fine in C++14 compiler. (See live demo here.) So, where does C++ standard says about this? If I remove static keyword from the declaration of char array in test class, compiler gives an error ISO C++ forbids zero size array when I use -pedantic-errors command line option in g++ & /Zaoption in MSVS 2010 compiler it says error C2133: 'test::a' : unknown size. So, my questions are:

1) what is the use of unknown size static array?

2) How do I later specify size of them & access that array elements? I am really getting confused.

3) Why removing static keyword leads to compilation errors?

It would be better if someone would explain it using simple example.

Thanks.

Upvotes: 4

Views: 887

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96258

The compiler doesn't care about the size. It's just a declaration for the static field, so telling it you have an array is enough. Size doesn't matter at this point.

You only have a declaration for the static field at this point. You never use those arrays and the compiler is permissive... it won't complain.

If you want to use them however, you'll need a definition. If you omit the size there, you'll get similar error messages you saw before.

There isn't anything special going on.

Upvotes: 4

Related Questions