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
};
The way to initialize class fields is with something called a static initializer. A static initializer is the keyword static followed by code in curly braces. You declare a class field much as you would declare a local variable. The chief difference is that field declarations do not belong to any method.
To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.
A class initialization block is a block of statements preceded by the static keyword that's introduced into the class's body. When the class loads, these statements are executed.
You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.
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.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With