views:

47

answers:

1

Say I have several objects within a class, each of which needs constructing with a different value. I can write something like this:

class b
{
public:
  b(int num)
    {
    // 1 for a.b1, and 2 for a.b2
    }
};

class a
{
public:
  b b1;
  b b2;
  a() : b1(1), b2(2)
    {
    }
};

However, is it possible to do the same thing if those multiple objects are stored in an array?

My first attempt at it doesn't compile:

class a
{
public:
  b bb[2];
  a() : bb[0](1), bb[1](2)
    {
    }
};
+2  A: 

You cannot do this directly; you need to initialize the array elements in the body of the constructor.

The elements of the array are default constructed before the body of the constructor is entered. Since your example class b is not default constructible (i.e., it has no constructor that can be called with zero parameters), you can't have an array of b as a member variable.

You can have an array of a type that is not default constructible in other contexts, when you can explicitly initialize the array.

James McNellis