https://stackoverflow.com/a/8839647/462608
Use the static initializer:
public class MyClass { static { //init } }
Can something similar be done in C++?
Actually, I need to initialize some variables, but I don't want to create an object.
https://stackoverflow.com/a/8839647/462608
Use the static initializer:
public class MyClass { static { //init } }
Can something similar be done in C++?
Actually, I need to initialize some variables, but I don't want to create an object.
If the variables are static
members, not only are you able to initialize them, but you must initialize them.
There's no direct equivalent of Java initializer lists, but something similar can be done calling a function to initialize a static member:
class X
{
static bool x;
}
bool foo()
{
//initialization code here
}
bool X::x = foo();
This is for cases with intense logic. If all you want is to initialize static
members, just do it similar to X::x
.
Actually, I need to initialize some variables, but I don't want to create an object.
If the variables are outside the class, initialize them directly (don't need calling code for that).
If the variables are static
members of the class, use one of the above approaches.
If the variables are non-static
members, they simply don't exist without an object.
Static variables of a class are initialized in .cpp file:
MyClass.h
class MyClass {
public:
static void f1();
static void f2();
private:
static int a1;
static int a2;
static int a3;
};
MyClass.cpp
int MyClass::a1 = 7;
int MyClass::a2 = 8;
int MyClass::a3 = MyClass::a1 + MyClass::a2;
void MyClass::f1()
{
a1 = 7;
}
void MyClass::f2()
{
cout << a2 << endl;
}
If you want non trivial initialization of static member variables - group them in inner class with constructor:
MyClass.h
class MyClass {
public:
static void f1();
static void f2();
private:
struct Data {
Data();
int a1;
int a2;
int a3;
};
static Data data;
};
MyClass.cpp
MyClass::Data MyClass::data;
MyClass::Data::Data() : a1(0), a2(0), a3(0)
{
// it is just an example ;)
for (int i = 0; i < 7; ++i)
{
a1 += 2;
s2 += 3;
a3 += a1 + a2;
}
}
void MyClass::f1()
{
data.a1 = 7;
}
void MyClass::f2()
{
cout << data.a2 << endl;
}