c++ – Static member initialization in main

Question:

How to initialize a non-const static member of a class before creating an instance of the class in the main function ?

For instance:

class A
{
protected:
 static int x;
 A(){}
public:
};
class B: public A
{
};

int main()
{
// нужно инициализировать x здесь
B b;
}

Answer:

Add a static function that will assign a value to x and call it:

class A
{
protected:
    static int _x;
    A() {}
public:
    static void InitX(int x)
    {
        _x = x;
    }
};

В main:

int main()
{
    A::InitX(5);
    B b;
}

If it is the initialization that is needed, then you have no control over when it is done, but it will definitely be done before main .

In your code, by the way, there is just not enough initialization, and without it the code will not be assembled. Add the following to the global scope:

int A::x = 0;
Scroll to Top