Reputation: 34527
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 make what I think is a unrelated change:
bool _inited = Test::_init();
it no longer compiles, giving me the expected error about trying to call a private method.
Upvotes: 4
Views: 189
Reputation: 48948
This code compiles and works the way I want it, but why?
Because where you are using it you are operating at class scope, as part of the class.
It would be the same if you were to write:
static void Test::foo() {
Test::_init(); // or just _init();
}
Here, the function foo
is obviously a part of the class, so you can access every member of Test
(be it private or public) in it.
You can even remove the Test::
, it is redundant because the compiler will already be looking in the scope of Test
for _init()
, when _inited
is initialized (because it's part of Test
).
Upvotes: 4
Reputation: 2010
The answer is simple. When you write
bool Test::_inited = Test::_init();
it means that the private static variable of class Test has a value equal to the value that _init() function returns. It is completely valid as you are not trying to access a private function from outside its scope. The Class_Name:: prefix puts them inside the class. They are just not in the class declaration. So in a way its like putting that whole statement inside the class.
Now when you write-
bool _inited = Test::_init();
the variable _inited is different from that of class Test. So it's taking its value from a private data method of a class which is forbidden unless a getter function is used for the assignment.
Upvotes: 1
Reputation: 779
I think the following sums it up pretty good. Taken form http://www.cplusplus.com/doc/tutorial/classes/
The scope operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition.
I think the same is applicable to everything within the Class, including the static field.
Upvotes: 1