-3

Below is a code section that has trouble retrieving the size of an array based on whether or not the array is static or not.

struct foo
{
    static const char* const a[30];
    const char* const b[30];
    const int ia = __countOf(a) // compiles
    const int ib = __countOf(b) // has compile errors related to initialization
};
noztol
  • 494
  • 6
  • 25

1 Answers1

5

The minimal example above does compile...

But what you really meant to ask was "why doesn't it compile when I reference foo::b"?

It's because all const members must be initialised in a constructor (and indeed in the initialisation list of the constructor, not in the body).

As of c++11 you can provide default values in the class definition:

#include <iostream>

struct foo
{
    static const char* const a[30]; // compiles 
    const char* const b[30] = {"Hello", "World" /*insert others here */ };
};


const char* const foo::a[30] = {
  "Hello", "Cruel", "World", /* etc */
};

int main()
{
  foo f;
  std::cout << f.b[0] << std::endl;
  std::cout << f.a[2] << std::endl;
  return 0;
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Well, compiling includes the linking stage, doesn't it? – πάντα ῥεῖ May 10 '16 at 16:52
  • @πάνταῥεῖ the code posted in the question linked for me also. Nothing referenced the missing member definitions. – Richard Hodges May 10 '16 at 16:53
  • Sure, if nothing references that, the linker won't complain. But the OP probably missed to point out it's referenced somewhere actually. – πάντα ῥεῖ May 10 '16 at 17:00
  • @RichardHodges this works for me the only thing that still had compile failures were the use of __countof on this array inside of the definition? by chance do you know why that happens aswell: this is what __countof maps to: (sizeof(*__countof_helper(_Array)) + 0) and char (*__countof_helper(_UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray]; – noztol May 10 '16 at 17:02
  • 1
    @user1881587 WTH is `__countof `?? – πάντα ῥεῖ May 10 '16 at 17:04
  • 1
    @user1881587 sorry fella, nothing brings down the "on hold" hammer faster than asking about code that's not in the question. I can't help any further on this question since it's been voted down (not by me!). Perhaps post another question containing a minimal, complete program (i.e. 15 lines) that shows the problem you have? – Richard Hodges May 10 '16 at 17:13