0

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
}

Edited by Narue: Fixed code tags

3
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Stogie2
0

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.

0

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 ) ;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.