0

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. :)

2
  • 3
    C++ doesn't allow arrays in classes without an explicit size. Commented Feb 23, 2014 at 21:44
  • If you need a dynamic size make the class into a template and then when you construct it you can set the size. Or you could malloc the memory and then copy the array inside thje constructor instead of using an initializer list. Commented Feb 23, 2014 at 21:46

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, #2 is the way to go in most cases, but it does depend on what one is trying to do.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.