Initialize array of char in initialization list of constructor in C++

FrozenHeart picture FrozenHeart · Nov 3, 2012 · Viewed 13.9k times · Source

Is it ok to use initialization like this?

class Foo
{
public:
   Foo() : str("str") {}
   char str[4];
};

And this?

int main()
{
   char str[4]("str");
}

Both give me an error in gcc 4.7.2:

error: array used as initializer

Comeau compiles both.

Answer

iammilind picture iammilind · Nov 3, 2012

In C++03, the non-static member array cannot be initialized as you mentioned. In g++ may be you can have an extension of initializer list, but that's a C++11 feature.

Local variable in a function can be initialized like this:

char str[] = "str"; // (1)
char str[] = {'s','t','r',0}; // (2)

Though you can mention the dimension as 4, but it's better not mentioned to avoid accidental array out of bounds.

I would recommend to use std::string in both the cases.