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
 
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.
 
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top