ladder
ladder

Reputation: 229

Initializer list in constructor to initialize private const c string error

my private members in my class:

const char arr1[];
const char arr2[];

my constructor:

className(const char a[], const char b[])
   :arr1(a), arr2(b)
{

}

The error message from console window is:

In constructor className::className(const char*, const char*):
error: incompatible types in assignment of const char* to const char [0]

Please help, what am I doing wrong?


On a side note, I found a solution... I used pointers as my private member vars, so *arr1 and *arr2 and that worked. :)

Upvotes: 0

Views: 889

Answers (2)

jrok
jrok

Reputation: 55395

First of all, you compiler should already choke on declarations of the members:

const char arr1[];
const char arr2[];

That's illegal C++, arrays as class members need to have their size spelled out.

Second, const char p[], when used in function declarations, literaly means const char* p. That is, a pointer to constant char. Arrays are not pointers, don't confuse the two. They decay to a pointer to their first element when passed to functions, though.

Upvotes: 0

Tim Čas
Tim Čas

Reputation: 10867

You are declaring your members as const char arr1[]. I am suprised that the compiler is even allowing you to make that declaration, as it should have had a fixed size in that form (like const char arr1[512]).

Depending on what you want to do, you'll either have to:

  1. declare your members as const char* arr1 -- note that this will not copy the strings; or
  2. use a string class (like std::string) and/or allocate memory for the class member, and copy

Upvotes: 2

Related Questions