Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 731
FrozenHeart Avatar asked Nov 03 '12 06:11

FrozenHeart


1 Answers

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.

like image 119
iammilind Avatar answered Sep 20 '22 23:09

iammilind