Reputation: 26723
Working in Xcode on Mac OS X Leopard in C++:
I have the following code:
class Foo{
private:
string bars[];
public:
Foo(string initial_bars[]){
bars = initial_bars;
}
}
It does not compile and throws the following error:
error: incompatible types in assignment of 'std::string*' to 'std::string [0u]'
I notice that removing the line bars = initial_bars;
solves the problem.
It seems like I am not doing the assignment correctly. How could I go about fixing this problem?
EDIT:
The variable bars is an array of strings. In the main function I initialize it like this:
string bars[] = {"bar1", "bar2", "bar3"};
But it can contain an arbitrary number of members.
Upvotes: 4
Views: 6187
Reputation: 21731
It is possible to "value-initialize" array members as follows:
class A {
public:
A ()
: m_array () // Initializes all members to '0' in this case
{
}
private:
int m_array[10];
};
For POD types this is important as if you don't list 'm_array' in the member initialization list then the array elements will have indeterminate values.
In general it's better to initialize members in the member-initialization-list, otherwise the members will be initialized twice:
A (std::vector<int> const & v)
// : m_v () // 'm_v' is implicitly initialized here
{
m_v = v; // 'm_v' now assigned to again
}
More efficiently written as:
A (std::vector<int> const & v)
: m_v (v)
{
}
Upvotes: 1
Reputation: 99092
Arrays behave like const pointers, you can't assign pointers to them. You also can't directly assign arrays to each other.
You either
bar
s you get and initialize your member array with its contentsstd
container like std::vector
Upvotes: 8