8

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
};
Roman Starkov
  • 59,298
  • 38
  • 251
  • 324
  • In C++ the struct instance with empty braces will normally not be zeroed, but will contain garbage values. Exceptions may be in a debug environment or similarly controlled situation. – Staffan E Jul 16 '10 at 12:11
  • @SEinarsson - oh... do you have a reference for that? The empty braces are recommended all over the web for initializing structs in C++. – Roman Starkov Jul 16 '10 at 12:58
  • Wait, now I'm not so certain. I've found people on the web saying I'm wrong but no formal definition for the {} pattern. The following question implies that structs-classes in C++ have zeroing default constructors, when used in a class initializer (see second answer) http://stackoverflow.com/questions/112085/is-this-c-structure-initialization-trick-safe Just disregard my above comment until I can clarify this. – Staffan E Jul 19 '10 at 07:41

4 Answers4

6

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
  • 246
  • 1
  • 3
4

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
  • 41,293
  • 8
  • 87
  • 103
1

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
  • 53,676
  • 39
  • 161
  • 238
0

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: Initializing static struct tm in a class

Community
  • 1
  • 1
m_pGladiator
  • 8,462
  • 7
  • 43
  • 61