Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can class fields be initialized?

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
};
like image 937
Roman Starkov Avatar asked Jul 16 '10 12:07

Roman Starkov


People also ask

How do you initialize a class field in Java?

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.

How do you initialize a class variable?

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.

How a class is initialized in Java?

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.

Can you initialize a class?

You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.


2 Answers

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.

like image 147
BeachBlocker Avatar answered Sep 29 '22 18:09

BeachBlocker


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;
};
like image 43
sje397 Avatar answered Sep 29 '22 16:09

sje397