static variable cannot be accessed directly from a code in class

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?
I could make another variable with the exact same name in another class, or just outside a class.

So how would you specify which of those variables with the exact same name is to be used?

1
2
3
4
5
6
7
8
9
10
11
class beans
{
  static int banana;
};

class eggs
{
  static int banana;
};

 int banana;


Three int variables all with the same name. When I say banana, which one do I mean?


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
Topic archived. No new replies allowed.