Apr 26, 2020 at 1:32pm UTC
Why a static variable as a class' member cannot be accessed directly from a line of code of a function inside class, instead it has to be access in the function defined outside the class' body using :: scope, what's the logical reason behind it?
Apr 26, 2020 at 5:39pm UTC
The question is a bit unclear. I think Repeater's answer is what abdul is looking for, but just another take on the question...
There is a peculiarity of how static variables need to be defined.
In C++98, the following code does not compile:
1 2 3 4 5 6 7 8
class Foo
{
static int bar = 3;
};
//int Foo::bar = 3;
int main() { }
Even in C++11/14, it does not compile.
3:22: error: ISO C++ forbids in-class initialization of non-const static member 'Foo::bar'
In C++17, this restriction was finally removed, and the code compiles.
If we search the error message about ISO C++ forbidding it... apparently the reasoning is:
PMF wrote:Reason is that putting such an initialization in the header file would duplicate the initialization code in every place where the header is included.
I guess something was changed in the linking process to remove this restriction in C++17, but I don't really know what specifically.
Last edited on Apr 26, 2020 at 5:43pm UTC