Initializing an array of classes in an initializer list.

I was just in another thread (http://cplusplus.com/forum/general/77527/) and came accross a problem in my answer that I'm not sure how to get around. The following yeilds a syntax error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
typedef double POINT[3];

class PLANE
{
  double A;    // Plane can be defined as
  double B;    // "Ax + By + Cz + D = 0"
  double C;
  double D;
public:
  PLANE(POINT p1, POINT p2, POINT p3); // Create a plane from 3 points
  bool isAbove(POINT p); // Tests whether a point is above, in front, or to the right of a plane
};

class POLYGON6 // 6 sided polygon (a cube will be our test object)
{
  PLANE plane[6];
public:
  // Defined with 8 points.  Could be less, but I'm just being casual right now.
  POLYGON6(POINT p1, POINT p2, POINT p3, POINT p4, POINT p5, POINT p6, POINT p7, POINT p8);
  bool isInPoly(POINT p);
};

POLYGON6::POLYGON6(POINT p1, POINT p2, POINT p3, POINT p4, POINT p5, POINT p6, POINT p7, POINT p8) :
  plane[0] (PLANE (p1, p2, p3)), // Front 3 
  plane[1] (PLANE (p1, p3, p4)),
  plane[2] (PLANE (p1, p4, p2)),
  plane[3] (PLANE (p8, p7, p5)), // Back 3
  plane[4] (PLANE (p8, p5, p6)),
  plane[5] (PLANE (p8, p6, p7))
{}


Line 24 gives a Syntax error: '[' expected a '('.
Line 24 gives a "Error: Only '()' is allowed as initializer for "POLYGON6::plane"
Line 25 gives a Error: member "POLYGON6::plane" has already been initialized

How else can I initialize an array of classes with constructors? My work-around was to use an initialization function instead of a constructor for PLANE.

As far as I know, you can't. If you are making an array, the objects must be default constructed.
closed account (zb0S216C)
GCC supports array initialiser-lists inside a constructor's initialiser-list as an extension. As far as I know of, there's no standard way of initialising an array inside a constructor. I haven't tried, but doesn't C++11 allow initialisation of class data members outside the constructor?

1
2
3
4
struct Test 
{
    int array[3] = {1, 2, 3}; // C++11 feature. Allowed?
};

Wazzak
I'm still on VS2010 so no C++11 here. Thanks for the info.
Topic archived. No new replies allowed.