Anton Eriksson
Anton Eriksson

Reputation: 169

What is the difference between declaring a static variable in a class in the .h file and a "global" variable in the .cpp file

I don't know if my title is expressed with the right terminology, if it isn't, please correct me so I can update it. However this is my question expressed with code examples: What is the difference, when it comes to the keyStates variable, between example A and B?

Example A (Where the "keyStates" variable is defined as a static variable in the class in the .h file):

// Input.h
class Input
{
public:
    static bool GetKeyDown(KeyCode keycode);
private:
    static std::unordered_map<KeyCode, KeyState> keyStates;
}

// Input.cpp
#include "Input.h"

bool Input::GetKeyPressed(KeyCode keyCode)
{
    for (auto Code : AllKeyCodes)
    {
        if (Code == keyCode)
        {
            return KeyState::PRESSED == keyStates.find(Code)->second;
        }
    }
    return false;
}

Example B (Where the "keyStates" variable is defined without static in the .cpp file):

// Input.h
class Input
{
public:
    static bool GetKeyDown(KeyCode keycode);
}

// Input.cpp
#include "Input.h"

std::unordered_map<KeyCode, KeyState> keyStates;

bool Input::GetKeyPressed(KeyCode keyCode)
{
    for (auto Code : AllKeyCodes)
    {
        if (Code == keyCode)
        {
            return KeyState::PRESSED == keys.find(Code)->second;
        }
    }
    return false;
}

Upvotes: 1

Views: 86

Answers (1)

smyatkin_max
smyatkin_max

Reputation: 365

Well, when you have a static member of a class (whether it's a field or a method), it is "global" for the whole class, so that:

  1. To access it from anywhere you need to use ClassName::method() or ClassName::field.
  2. You can share or restrict access to this member with access modifiers: private, public and ptorected.
  3. This member belongs to the class, not to any specific objects. You cannot use this from such methods The full list of restrictions is there: https://en.cppreference.com/w/cpp/language/static

The static global variable, on the other hand, is like a usual global variable, except it "exists" only for the current compilation unit. You can not use it from anywhere except this particular .cpp file. With a usual global variable if there are two compilation units (cpp files) with the same global variable int a, the code won't compile. Here is more on that: C/C++ global vs static global

Also, you can use anonymous namespaces anywhere where you would use static global variables (or methods, or even types).

UPD.: Yet another difference here. When you put your keyStates into cpp file as a static global (or part of anonymous namespace), the implementation detail is hidden from class definition and the .h file. So you can change it whenever you wish w/o changing the interface and having to recompile anything except the cpp file.

Upvotes: 1

Related Questions