I have a bit of a problem with my constructor. In my header file I declare:
char short_name_[2];
- and other variables
In my constructor:
Territory(std::string name, char short_name[2], Player* owner, char units);
void setShortName(char* short_name);
inline const char (&getShortName() const)[2] { return short_name_; }
In my cpp file:
Territory::Territory(std::string name, char short_name[2], Player* owner,
char units) : name_(name), short_name_(short_name),
owner_(owner), units_(units)
{ }
My error:
Territory.cpp: In constructor ‘Territory::Territory(std::string, char*, Player*, char)’: Territory.cpp:15:33: error: incompatible types in assignment of ‘char*’ to ‘char [2]’
I already figured out that char[2] <=> char*
but I'm not sure how to handle this about my constructor and get/setters.
When a function wants an array as argument, it gets a pointer to the first element of an array instead. This pointer cannot be used to initialize an array, because it's a pointer, not an array.
You can write functions that accept references to arrays as arguments:
The problem here is, that this array reference cannot be used to initialize another array.
C++ 11 introduced
std::array
to eliminiate this and other problems of arrays. In older versions, you will have to iterate through the array elements and copy them individually or usestd::copy
.Raw arrays in C++ are kind of annoying and fraught with peril. This is why unless you have a very good reason to you should use
std::vector
orstd::array
.First off, as others have said,
char[2]
is not the same aschar*
, or at least not usually.char[2]
is a size 2 array ofchar
andchar*
is a pointer to achar
. They often get confused because arrays will decay to a pointer to the first element whenever they need to. So this works:But the reverse does not:
Adding to the confusion, when declaring function parameters,
char[]
is equivalent tochar*
. So in your constructor the parameterchar short_name[2]
is reallychar* short_name
.Another quirk of arrays is that they cannot be copied like other types (this is one explanation for why arrays in function parameters are treated as pointers). So for example I can not do something like this:
Instead I have to iterate over the elements of
foo
and copy them intobar
, or use some function which does that for me such asstd::copy
:So in your constructor you have to manually copy the elements of
short_name
intoshort_name_
:As you can see this is all very annoying, so unless you have a very good reason you just should use
std::vector
instead of raw arrays (or in this case probablystd::string
).