How to initialize class fields?

A little about the basic question, but it's hard for me to find a definitive answer.

Does the initializer list the only way to initialize class fields in C ++, except for assignment in methods?

If I use the wrong terminology, here is 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 good way to initialize a struct field using a structure 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 }; 
+6
c ++ initialization ctor-initializer
source share
4 answers

In C ++ x0, the second method should work as well.

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

In your case with your compiler: Yes.

+5
source share

Static elements can be initialized in different ways:

 class Test { .... static int x; }; int Test::x = 5; 

I don’t know if you call it "enjoyable", but you can initialize the structure elements quite cleanly like this:

 struct stype { const char *str; int val; }; stype initialSVal = { "hi", 7 }; class Test { public: Test(): s(initialSVal) {} stype s; }; 
+3
source share

Just mention that in some cases you have no choice but to use initializer lists to set the value of an element when building:

 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. } }; 
+1
source share

The recommended and preferred way is to initialize all the fields in the constructor, as in the first example. This is true for structures. See Here: Initializing the tm Static Structure in the Class

0
source share

All Articles