Search code examples
c++global-variablesprivate-members

Unexposed private member variables vs. global variables in the source file


I am looking at some code in a company I am currently working at and I see a few (not a lot) declarations of static global variables in the *.cpp files (for example, to store a list of listeners) where the .h/.cpp files belong to a class. If a variable (static or otherwise) that is used only by class itself, I always declare it as private.

Is there an advantage to this over declaring the variable private? Is this bad practice? Or is this normal when declaring static variables that are used by the class only and nobody else?

EDIT: In my question I asked about static, but what if it is a non-static global variable in the .cpp file instead of it being a private member of the class? Is that bad practice or considered ok? Any advantages in this case?


Solution

  • The main advantage to this way is reducing the amount of "unnecessary" stuff in the *.h file. This might slightly improve compile times and/or rebuild complexity when files or modified, and it may make the header file slightly easier to read.

    (In my opinion, these advantages are small, and I will usually prefer the clarity of putting things that logically are related to a class in that class's scope.)

    However, static global variables are deprecated and bad practice in C++. If there is no other appropriate scope, an anonymous namespace should be used.

    // Instead of this:
    static std::list<MyClass*> MyClass_population;
    
    // Do this:
    namespace { // anonymous
        std::list<MyClass*> MyClass_population;
    }