Reputation: 61462
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
};
Upvotes: 8
Views: 29287
Reputation: 55746
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.
}
};
Upvotes: 1
Reputation: 41832
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;
};
Upvotes: 4
Reputation: 246
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.
Upvotes: 6
Reputation: 8620
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
Upvotes: 0