initializing member arrays

K

Klaus Rudolph

Hi all,

I have 2 classes, the second one should include an
array of the first on. The first class should not have a default
constructor. How could I use an array of the first classes?
If it is impossible to initialize the array before entering the
constructor , it
would never be possible to use arrays of classes in C++ whitout using a
default constructor.
Is that correct?



class A {
protected:
int a;
public:
A(int _a): a(_a) {}
};

class B {
protected:
A arr[2];
public:
B(int _a1, int _a2): arr(?????????????) {} //<-------------------
};

int main() {
B b(1,2);
return 0;
}

The marked line is my problem. Is there no way to initialize the array?
Is using a vector<> the only solution here?

Regards
Klaus
 
R

Ron Natalie

Klaus Rudolph said:
Hi all,

I have 2 classes, the second one should include an
array of the first on. The first class should not have a default
constructor. How could I use an array of the first classes?

Can't be done. Arrays are half-baked types in C++. This is
one of their failings. Your choices are to set the values in the
body of the constructor, or to replace it with a type (like vector)
that has reasonable initialization semantics.
 
D

David Fisher

Klaus Rudolph said:
class A {
protected:
int a;
public:
A(int _a): a(_a) {}
};

class B {
protected:
A arr[2];
public:
B(int _a1, int _a2): arr(?????????????) {} //<-------------------
};

int main() {
B b(1,2);
return 0;
}

The marked line is my problem. Is there no way to initialize the array?
Is using a vector<> the only solution here?

You could create a protected default constructor for class A, and make B a
friend of A ... you might also want an init() function which acts as a
constructor in this case (unless you are happy to initialise arr[] with
assignments to temporary objects which use the non-default constructor).

David F
 
J

Jerry Coffin

Hi all,

I have 2 classes, the second one should include an
array of the first on. The first class should not have a default
constructor. How could I use an array of the first classes?
If it is impossible to initialize the array before entering the
constructor , it
would never be possible to use arrays of classes in C++ whitout using a
default constructor.
Is that correct?

Yes, it is.

[ ... ]
The marked line is my problem. Is there no way to initialize the array?
Is using a vector<> the only solution here?

It may not be the only one but it's almost certainly the preferred one.
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top