Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing member array in constructor initialization list (before C++11)

As far as I know, before C++11, the only way to initialize a member array in a constructor initialization list was to do, e.g., the following:

MyClass::MyClass(int arg) : member(arg), memberArray() {
    // anything else that needs to be done in the c'tor
}

However, I have had several people tell me they frown on this method, and that it would possibly be safer/more readable to zero-initialize it in a for loop in the body of the constructor.

I don't have C++11 support available yet, so I can't use an initializer list, etc. Are there any guidelines anyone has heard of that discourage initializing member arrays in the constructor initializer list?

Also, testing indicates no, but there shouldn't be any problem using this syntax for a multi-dimensional array, correct? (E.g., this isn't some part of the standard that certain compilers screw up for some reason...)

I don't mean for this to be a subjective question - I'm simply interested to know if there is a good reason to use/not to use the above syntax.

Many thanks for any help.

like image 673
llakais Avatar asked Nov 14 '12 14:11

llakais


1 Answers

You may want to take a look as this related question on StackOverflow : using static functions to initialize your member arrays in initialization list can achieve what you are looking for :

class MyClass
{
   typedef std::array< int, 2 > t_myA;
   static t_myA fillFunction(){ static t_myA const ret = {1,2}; return ret; };

   t_myA myArray;

   public MyClass();
}

MyClass::MyClass()
 : myArray( fillFunction() )
{
}
like image 156
Mickaël Le Baillif Avatar answered Sep 29 '22 01:09

Mickaël Le Baillif