Why is it allowed to call a private static method when initializing a private static member?

This code compiles and works the way I want it, but why?

#include <iostream>

class Test {
private:
  static bool _inited;
  static bool _init() {
    std::cout << "init!" << std::endl;
    return true;
  }
};

bool Test::_inited = Test::_init();

int main(int argc, char** argv) {
}

And if I do what I think, this is an unrelated change:

bool _inited = Test::_init();

it no longer compiles, giving me the expected error in an attempt to call a private method.

+4
source share
3 answers

The answer is simple. When you write

bool Test::_inited = Test::_init();

, Test , , _init(). , - . Class_Name:: . . , , .

, -

bool _inited = Test::_init();

_inited Test. , , , .

+1

, , ?

, , .

, :

static void Test::foo() {
    Test::_init(); // or just _init();
}

foo, , , Test ( ).

Test::, , Test _init(), _inited ( Test).

+4
+1

Source: https://habr.com/ru/post/1667677/


All Articles