Can you initialize and array in a constuctor?

What am I doing wrong? Can't I initialize an array in the constructor?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>


class TypeHolder
{
  private:

	int Items[5];

	public:
            TypeHolder::TypeHolder()
	    {
	       Items[5]={5,6,7,8,9};
	    }

};

int main()
{
   TypeHolder Books;
 
   return 0;
}
In C++11 you can initialize the array like this.
1
2
3
4
TypeHolder::TypeHolder()
:	Items{5,6,7,8,9}
{
}


Before C++11 you would have to assign each elements one by one.
1
2
3
4
5
6
7
8
TypeHolder::TypeHolder()
{
	Items[0] = 5;
	Items[1] = 6
	Items[2] = 7;
	Items[3] = 8;
	Items[4] = 9;
}
ok thanks!! :)

Only error I really see is that you try to initialize Items[5] with 5 values. After the array is declared it has 5 elements that range over Items[0] to Items[4] so Item[5] is actually outside the array. Also, you can only assign a single value to a single element.
Topic archived. No new replies allowed.