tags:

views:

305

answers:

2

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.

+7  A: 

Arrays behave like const pointers, you can't assign pointers to them. You also can't directly assign arrays to each other.

You either

  • use a pointer member variable
  • have a fixed size of bars you get and initialize your member array with its contents
  • just use a reference to a std container like std::vector
Georg Fritzsche
thank you very much! used vectors and it solved the problem
yuval
A: 

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)
{
}
Richard Corden