Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array in a class constructor?

Tags:

c++

oop

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.

like image 673
Yuval Karmi Avatar asked Jan 23 '23 04:01

Yuval Karmi


1 Answers

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
like image 114
Georg Fritzsche Avatar answered Jan 25 '23 22:01

Georg Fritzsche