“static” in C++


Inside struct/class

  • Case 1: without “static”
  • Case 2: with “static”
  • Case 3: with “static” — better way to call static member

Outside struct/class

  • Case 1: without “static”
  • Case 2: with “static”

— — — — — — — — — — — — — — — — — — — — — — — — — —

“static” could has 2 different meaning corresponding to it’s context:

  • inside struct/class
  • outside struct/class

“static” inside struct/class

The “static” member will share memory with all the instance of the struct/class. No matter how many instances of struct/class are created, there is only one “static” member.

  • If an instance changes the “static” member, this change can be see from all the instances.

Case 1: without “static”

Both e and e1 has their own member of x and y:

Case 2: with “static”

Even through we have 2 entities e and e1, they are pointing at the same x and y of Entity. Therefore we printed the same value.

Case 3: with “static” — better way to call static member

We usually use “Entity::x” to call the static variables, as if x and y are variables under a namespace “Entity”

⚠️ Note:

  • static function also works in similar way
  • static function CANNOT access non-static variable

“static” outside struct/class

The “static” member is internal and ONLY visible in it’s own translation unit(in most case also means it’s own *.cpp file).

  • Linker doesn’t need to link it to other file, because there won’t be any other file using this “static” member

Case 1: without “static”

Following situation caused error due to the duplicated declaration of variable “s_Variable”

Case 2: with “static”

static variable is ONLY available in Static.cpp’s scope. Therefore the Linker won’t find any conflict.

🦠 🈲️ 🌎