How can class fields be initialized?

Roman Starkov picture Roman Starkov · Jul 16, 2010 · Viewed 22.9k times · Source

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
};

Answer

BeachBlocker picture BeachBlocker · Jul 16, 2010

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.