Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't defining array without size with initializer work inside class definition? [duplicate]

Consider the code:

struct Foo
{
    const char str[] = "test";
};

int main()
{
    Foo foo;
}

It fails to compile with both g++ and clang++, spitting out essentially

error: array bound cannot be deduced from an in-class initializer

I understand that this is what the standard probably says, but is there any particular good reason why? Since we have a string literal it seems that the compiler should be able to deduce the size without any problem, similarly to the case when you simply declare an out-of-class const C-like null terminated string.

like image 313
vsoftco Avatar asked Dec 05 '25 20:12

vsoftco


1 Answers

The reason is that you always have the possibility to override an in-class initializer list in the constructor. So I guess that in the end, it could be very confusing.

struct Foo
{
   Foo() {} // str = "test\0";

   // Implementing this is easier if I can clearly see how big `str` is, 
   Foo() : str({'a','b', 'c', 'd'}) {} // str = "abcd0"
   const char str[] = "test";
};

Notice that replacing const char with static constexpr char works perfectly, and probably it is what you want anyway.

like image 139
sbabbi Avatar answered Dec 08 '25 11:12

sbabbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!