Initialize array of char in initialization list of constructor in C++
Solution 1
This code is valid C++03 and gcc is simply not conformant here.
The language that allows this syntax for initializing character arrays is the same as allows it for any other type; there are no exceptions that would prohibit it from being used on character arrays. ()
and =
initialization are equivalent in these cases and the character array should simply be initialized according to 8.5.2.
Here's a confirmed gcc bug report that covers this.
Solution 2
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.
Solution 3
In C++03, that is not possible. Comeau might compile it because of non-Standard extension.
In C++11, you can do this:
Foo() : str({'s','t','r'}) {} //C++11 only
Or, you may prefer this intead:
class Foo
{
public:
Foo() {}
char str[4] = "str"; //in-class initialization (C++11 only)
};
Also, you might consider using std::string
or std::vector<char>
irrespective of the version of C++ you're using.
FrozenHeart
Updated on June 09, 2022Comments
-
FrozenHeart almost 2 years
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.