initialize an array member


A

Avner Flesch

Hi,

Do you know how can I intialize an array member:
for example
class A
{
public:
A(int x);
};

class B
{
public:
B();
private:
A a[2];
};

how do I intialize a?


Thanks

Avner
 
Ad

Advertisements

M

Mike Wahler

Avner Flesch said:
Hi,

Do you know how can I intialize an array member:
for example
class A
{
public:
A(int x);
};

class B
{
public:
B();
private:
A a[2];
};

how do I intialize a?

Same way you initialize any other member(s), with a constructor.

B::B()
{
a[0] = A(1);
a[1] = A(2);
}

This isn't technically 'initialization', it's assignment, but
its the best that can be done with an (non static) array member.

The language does not provide an initializer list syntax
for arrays. Maybe consider a container (or perhaps a std::pair)
instead.

-Mike
 
R

Rolf Magnus

Avner said:
Hi,

Do you know how can I intialize an array member:
for example
class A
{
public:
A(int x);
};

class B
{
public:
B();
private:
A a[2];
};

how do I intialize a?

You can't. C++ doesn't offer a way to initialize array members in the
initializer list. You have to get the members default-constructed and
then set whatever you need in the constructor body.
 
R

Rolf Magnus

Mike said:
Avner Flesch said:
Hi,

Do you know how can I intialize an array member:
for example
class A
{
public:
A(int x);
};

class B
{
public:
B();
private:
A a[2];
};

how do I intialize a?

Same way you initialize any other member(s), with a constructor.

The difference is that array members can only be default initialized.
B::B()
{
a[0] = A(1);
a[1] = A(2);
}

This isn't technically 'initialization', it's assignment, but
its the best that can be done with an (non static) array member.

"technically" or not. It's not initialization. The initialization
happend before the constructor of B was entered.
The language does not provide an initializer list syntax
for arrays. Maybe consider a container (or perhaps a std::pair)
instead.

I guess if the number was only 2 anyway, just two separate member
variables would be the easiest way.
 
Ad

Advertisements

E

EventHelix.com

I don't think there is a way to initialize an array with anything
other than a default constructor.

You could change the array to an array of pointers and then fill
in the array by new for individual objects at run-time.

Sandeep
 

Top