-3

This may be a silly doubt but I am not able to understand that why I am not able to access a private static data member outside the class when I am allowed to define it.

For ex: in the following code:

class foo
{
    static int A;
    public:
       int getA{return A;}
};
//This is allowed
int foo:A=0;
int main()
{
   //This gives error
   cout<<foo:A;
}
Rahul Jain
  • 67
  • 1
  • 2
  • 8
  • 3
    Why do you think you should be able to access it? C++ it pretty clear on the matter so I'm not sure what the confusion is. If a member is private but are still able to directly access it from outside the class that would make declaring it private pretty useless now wouldn't it. – Captain Obvlious Oct 20 '15 at 23:22
  • 2
    This makes no sense and is not even close to compiling. Please edit your example to actually show what you want to demonstrate. – Baum mit Augen Oct 20 '15 at 23:23
  • This is what I am concerned about. If the member is private, then why are we allowed to define it outside the class. Shouldn't this violate the specifier rules? – Rahul Jain Oct 20 '15 at 23:33

1 Answers1

2
int foo::A = 0;

allocates storage for the member variable A, and initializes it with 0 (actually a static is by default initialized with 0, so the assignment is superfluous). You do this only once in the implementation .cpp file. Then everyone will be able to instantiate your class without any linker issues. Note that you cannot do this again, i.e. assigning later foo::A = 42; will not compile, so you don't break any access rules. The fact that you must explicitly allocate storage is a language rule, which in my opinion creates more confusion (I'd make the compiler automatically allocate the storage when you declare the static).

So, to conclude, being allowed to define a private member is by far not as dangerous as being able to later access it/modify it, and is very different from the latter. The object is already sealed for the outside world once the member has its storage allocated.

vsoftco
  • 55,410
  • 12
  • 139
  • 252