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;
}
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments