How to Initialize Static Variables

Initialize static variables in C++ class?

They can't be initialised inside the class, but they can be initialised outside the class, in a source file:

// inside the class
class Thing {
static string RE_ANY;
static string RE_ANY_RELUCTANT;
};

// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";

Update

I've just noticed the first line of your question - you don't want to make those functions static, you want to make them const. Making them static means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const simply means that they can't modify any members, but can still access them.

When are static variables initialized?

From See Java Static Variable Methods:

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object.

Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.

What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.

In case of inner classes, they can not have static fields

An inner class is a nested class that is not explicitly or implicitly
declared static.

...

Inner classes may not declare static initializers (§8.7) or member interfaces...

Inner classes may not declare static members, unless they are constant variables...

See JLS 8.1.3 Inner Classes and Enclosing Instances

final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.

final class Demo
{
private final int x;
private static final int z; //must be initialized here.

static
{
z = 10; //It can be initialized here.
}

public Demo(int x)
{
this.x=x; //This is possible.
//z=15; compiler-error - can not assign a value to a final variable z
}
}

This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.

How to initialize private static members in C++?

The class declaration should be in the header file (Or in the source file if not shared).

File: foo.h

class foo
{
private:
static int i;
};

But the initialization should be in source file.

File: foo.cpp

int foo::i = 0;

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the static int i must be done outside of any function.

Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const integer type (bool, char, char8_t [since C++20], char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.). You can then declare and initialize the member variable directly inside the class declaration in the header file:

class foo
{
private:
static int const i = 42;
};

How to declare and initialize a static member in a class?

One can definitely have class static members which are not CV-qualified (non const and not volatile). It is just that one should not initialize them (give them value) when one declare them inside the class, based on current ISO C++ regulations. In Comparison, it is OK to do so for non static data members(regardless of CV-qualification) Since C++11.

Because static data members do not belong to any object, with the right access they can be assigned (and if they are not constant, they can be manipulated) outside of the class(keeping in mind the right scope operator). Also regardless of public/private declaration and CV-qualification, static data members can be initialized outside their class.

So one way for initializing static data members, is to do so in the same block-scope/namespace where their classes(outer class in case of sub-classes) are situated, but not inside any class scope.

For example:

class Graph {
public:
class Node {
public:
static int maxNumberOfNeighbors;
.
.
.
};
.
.
.
};

int Graph::Node::maxNumberOfNeighbors = 4;
//also int Graph::Node::maxNumberOfNeighbors(4);


Good luck!

How to initialize a static variable with another static variable?

You are experiencing effects of a static initialization order fiasco.

The usual work-around is to substitute your static variables with functions that have a static variable in the scope, initialize, and return it.


Here is how it could be done for your example: Live Example (order1)
Live Example (order2)

class Static1
{
public:
static std::string my_string();
};

...

std::string Static1::my_string()
{
static const std::string my_string = "aaa";
return my_string;
}

...

class Static2
{
public:
static std::string my_string();
};

...

std::string Static2::my_string()
{
static const std::string my_string = Static1::my_string();
return my_string;
}

...

std::cout << std::to_string(Static2::my_string() == "aaa") << std::endl;

How java initialize static variables and static method?(with simple code)

When Java executes code it is from top to bottom. So when it initialises variables it does so from top to bottom. However, when you read an unitilised value it will be 0, null or false as the memory is first filled with zeros. Note: the static fields of a class have their own special object which you can see in a heap dump.

so when you try to set

first = 0; // second hasn't been set yet
second = 2;
third = 2; // second has been set to 2.

The addition of the method only prevents the compiler from detecting you are trying to use a variable before it was initialised.

When are static variables initialized in Python?

Before.

The __init__ method isn't run until Foo is instantiated. i=1 is run whenever the class definition is encountered in the code

You can see this by adding print statements:

print('Before Foo')
class Foo:
i = 1
print(f'Foo.i is now {i}')

def __init__(self):
print('Inside __init__')
self.i += 1
print(f'i is now {self.i}')
print('After Foo')

print('Before __init__')
foo = Foo()
print('After __init__')

which prints:

Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__

Notice however, that your self.i += 1 does not modify the class attribute Foo.i.

foo.i # This is 2
Foo.i # This is 1

c# initialize static variable from different classes

This is because the static constructor is called automatically before the first instance is created or any static members are referenced..

This means that when an instance of otherClass invokes IDs.someID = sym; the first operation that gets executed is the static constructor, i.e. the code inside static IDs().

At this point the static variable has not yet been initialized, and you are basically executing log.info(null);.

After the static constructor completes, the variable is initialized, so you should be able to see its value inside otherMethod, after the first reference of IDs.


Given the OP's requirement:

I want to use the value passed in someID in a switch statement

The solution could be to simply execute a static method whenever a new value is set, with the help of explicit getters and setters:

public static class IDs
{
private static string _someID; // backing field

public static string SomeID
{
get { return _someID; }

set
{
_someID = value;
DoSomethingWithSomeID();
}
}

private static DoSomethingWithSomeID()
{
// Use SomeID here.

switch (IDs.SomeID)
{
...
}
}
}

public class OtherClass
{
public void OtherMethod(string sym)
{
// This will set a new value to the property
// and invoke DoSomethingWithSomeID.
IDs.SomeID = sym;
}
}

DoSomethingWithSomeID will be invoked every time someone sets a new value to SomeID.



Related Topics



Leave a reply



Submit