Static class fields are always initialized before calling the main function.
This is due to the fact that static fields, in their essence, are the same global variables, only with a name in a special format. Accordingly, they are stored in the same place and in the same way - being “sewn” in the data section of the executable file.
We found out when the value of static fields is given. We now turn to how to do it.
We cannot specify the value of the field in the constructor of the owning class — the static field is not only not a single instance of the class, it is also known until the start of the start function. We also cannot set the value in the class declaration itself, since the field is stored in one place, and it is accessed from many places; Who among the applicants will be responsible for initializing the memory cell with a variable? Note: at least it was before C ++ 14, but how it is implemented there is a separate question .
Therefore, both initialization and reservation of a static class field is performed similarly to those for global variables (another point of their similarity), namely, by mentioning it in some .cpp file. Like that:
int A::_x; // Значение поля будет определено позднее
Or so:
int A::_x = 12; // Значение поля «вшито» в исполняемый файл
Or even like this:
// myStaticFunction — статический метод класса A. // Можно уверенно утверждать, что все указанные в нём // действия выполняются строго до вызова функции main. int A::_x = A::myStaticFunction();
That is, the field type is indicated first, then its full name with all namespaces, and, finally, what this field will be initialized with - a constant (more precisely, a literal), the return value of the function or nothing at all.
Let us dwell on the second method, as the most consistent with the requirements of the author of the question. Initialization can be done not just by any function (except for non-static methods for obvious reasons), but in general by any functional object.
However, there is one significant limitation. According to the standard, the order of initialization of static fields is reliably known only within (simplifying) one .cpp file. As a result, by the time our function is called, only those fields that are specified in exactly the same way, but higher in the same file, are reliably initialized. The order of initialization of fields and variables from other .cpp files depends on the compiler and the order of listing the files with source codes in the project. All this should be taken into account when accessing other static fields and global variables from a function.
mainyou want to see? You can just do it earlier throughint A::x = A::initX(42);(borrowed the name from the @ixSci response). - αλεχολυτ42calculated directly inmain; the main thing is that the essence is clear - swaq