2

I can declare private static member variables in a class, but what does it mean?

What is the difference private static and public static member variables?

0

4 Answers 4

4

It means these variables cannot be accessed anywhere except within the class itself.

public members can be accessed from outside the class.
protected members can be accessed in the class and its derived classes &
private members can be only accessed within the class.

Note that the member being static or not the same Access Specification rules apply to it.
static implies the storage specification and that the some member will be shared across all the instances of the class it does not change where the member can be accessed.

Good Read:

What are access specifiers? Should I inherit with private, protected or public?

2

A private variable means it can only be accessed within the scope of the class it is declared in, that is, any functions declared outside the class cannot access (read or write) the private variable.

Declaring a variable as static means that it will hold the same value across all instances of that class.

1

You may want to do that if you need to hide information (private) and to have a class variable instead of an object variable (static)

1

Imagine you have a class A with a static int member called a

    class A {
        public:
        static int a;
    };

and lets say from your main function you access this as you do using

   int new_variable = A::a;

This works fine because your access specifier is public.

Now change it from public to private (or protected) and your code won't compile because private members can only be accessed by the class itself.

Not the answer you're looking for? Browse other questions tagged or ask your own question.