Search code examples
c++staticvisibilityprivate

Are private variable visible outside of the class if they are static?


In the following example (taken from here) we have a private static variable x and then we change its name outside of the class. What confuses me is why is it allowed to change a private variable outside of the class? What is then the reason to declare it a private.

// static_member_functions.cpp
#include <stdio.h>

class StaticTest
{
private:
    static int x;
public:
    static int count()
    {
        return x;
    }
};

int StaticTest::x = 9;

int main()
{
    printf_s("%d\n", StaticTest::count());
}

Solution

  • This is not "changing the variable", it's defining it.

    Every static member must be defined outside the class (static int x; is just a declaration; if you remove int StaticTest::x = 9; there will be a linker error saying something like "undefined reference to StaticTest::x").


    Try changing it in the main, for example:

    StaticTest::x = 13;
    

    and you'll get the error, you expected (error: ‘int StaticTest::x’ is private).