4

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.

1
  • 1
    For starters, the declaration string bars[] itself is an error in ISO C++ compliant code - the fact that your compiler lets you do it (and, judging by the error message, treats it as string bars[0]) means that it offers that as an extension. Commented Sep 24, 2009 at 16:30

2 Answers 2

8

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

Comments

1

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

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.