Click to See Complete Forum and Search --> : Initialization of an array.


dav79
April 5th, 2003, 08:20 AM
Hi there..

struct A{
A(int){}
};

struct B{
B() : ????
A a[10];
};

How can I initialize array of A in initialization list?

SeventhStar
April 5th, 2003, 09:17 AM
be more specific... what exactly do you want to do? I'm not sure i understand.

mwilliamson
April 5th, 2003, 09:44 AM
he wants to pass data to a constructor, but has an array of 10 objects. I don't know how to do this on the stack.

Paul McKenzie
April 5th, 2003, 11:01 AM
Originally posted by dav79
Hi there..

struct A{
A(int){}
};

struct B{
B() : ????
A a[10];
};

How can I initialize array of A in initialization list? You can't. You have to initialize A in the constructor body. But then your code will not compile, due to the fact that your A class has no default constructor, and you are attempting to create an array of A. Without a default constructor, your A array is unusable.

So you have a choice:

a) Give your A array a default constructor (a constructor that will take no arguments), and initialize the A array in the body of the B constructor, or

b) Use vectors. Then you can initialize the vector without adding a default constructor to A. Here is one way to use the vectors to do what you want.

#include <vector>

struct A{
A(int){}
};

struct B {
B() : a(10) { a[0] = 0; a[1] = 12; /*etc*/ }
// If you want to initialize the A to a single value:
// B() : a(10, 0) { } // Initialize all 10 elements to 0
std::vector<A> a;
};

There are probably other methods. Maybe the fixed array class at www.boost.org has a way of doing this. In any event, you can't initialize 'C' arrays in the initialization list.

Regards,

Paul McKenzie

SeventhStar
April 7th, 2003, 01:41 AM
ahaaaaaaa! now I get it! I was soooo confused when I saw this that couldn even think! :D

struct B{
B() : ????
A a[10]; // its weird
};

dav79
April 7th, 2003, 02:46 AM
Thanks a lot guys..