I am looking for the correct way to initialize an array data member and why the following code produces the listed error.

Thanks...

typedef struct tagsX
{
   tagsX(int u, int v): a(u), b(v) {}
   int a ;
   int b ;
} sX ;

typedef struct tagsY
{
   tagsY(sX *p, sX *q): c(p), d(q) {}
   sX *c ;
   sX *d ;
} sY ;

class Z
{
public:
   Z() ;
   sX e ;
   sX f ;
   sX g ;
   sX h ;
   sY i[2] ;
};

Z::Z() :
     e(0,0)
   , f(0,0)
   , g(0,0)
   , h(0,0)
   , i( ( &e, &f ),
        ( &g, &h ) )
{		// error C2536: 'Z::i' : cannot specify explicit initializer for arrays
}

Recommended Answers

All 3 Replies

You can't initialize an array member in the initialization list. It has to be done in the body of your constructor. If you're creating an array of a user-defined type, that type must also support default construction.

Hey those variable names don't look very descriptive, sometimes a meaningful name is helpful.

So the only way to initialize an array data member is to explicitly initialize each array element using the assignment operator and a temporary object as shown?

Thanks...

typedef struct tagsX
{
   tagsX(): a(0), b(0) {}
   tagsX(int u, int v): a(u), b(v) {}
   int a ;
   int b ;
} sX ;

typedef struct tagsY
{
  tagsY() : c(NULL), d(NULL) {}
  tagsY(sX *p, sX *q): c(p), d(q) {}
   sX *c ;
   sX *d ;
} sY ;

class Z
{
public:
   Z() ;
   sX e ;
   sX f ;
   sX g ;
   sX h ;
   sY i[2] ;
};

Z::Z() :
     e(0,0)
   , f(0,0)
   , g(0,0)
   , h(0,0)
{
   i[0] = tagsY( &e, &f ) ;
   i[1] = tagsY( &g, &h ) ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.