views:

89

answers:

4

A bit of a basic question, but I'm having difficulty tracking down a definitive answer.

Are initializer lists the only way to initialize class fields in C++, apart from assignment in methods?

In case I'm using the wrong terminology, here's what I mean:

class Test
{
public:
    Test(): MyField(47) { }  // acceptable
    int MyField;
};

class Test
{
public:
    int MyField = 47; // invalid: only static const integral data members allowed
};

EDIT: in particular, is there a nice way to initialize a struct field with a struct initializer? For example:

struct MyStruct { int Number, const char* Text };

MyStruct struct1 = {};  // acceptable: zeroed
MyStruct struct2 = { 47, "Blah" } // acceptable

class MyClass
{
    MyStruct struct3 = ???  // not acceptable
};
A: 

The recommended and preferred way is to initialize all fields in the constructor, exactly like in your first example. This is valid also for structs. See here: http://stackoverflow.com/questions/2105077/initializing-static-struct-tm-in-a-class

m_pGladiator
+1  A: 

Static members can be initialised differently:

class Test {
    ....
    static int x;
};

int Test::x = 5;

I don't know if you call this 'nice', but you can initialise struct members fairly cleanly like so:

struct stype {
const char *str;
int val;
};

stype initialSVal = {
"hi",
7
};

class Test {
public:
    Test(): s(initialSVal) {}
    stype s;
};
sje397
"Nice" is subjective of course. Thanks for showing how to initialize structs - I find this rather un-nice, but given that I have no choice... :)
romkyns
+2  A: 

In C++x0 the second way should work also.

Are initializer lists the only way to initialize class fields in C++?

In your case with your compiler: Yes.

BeachBlocker
A: 

Just to mention that in some cases, you have no choice but to use initializer lists to set a member's value on construction:

class A
{
 private:

  int b;
  const int c;

 public:

 A() :
  b(1),
  c(1)
 {
  // Here you could also do:
  b = 1; // This would be a reassignation, not an initialization.
        // But not:
  c = 1; // You can't : c is a const member.
 }
};
ereOn