Search code examples
c++classglobal-variablesstatic-variables

Static global variable in a class C++


I am trying to create a variable which will be shared by all instances of a class, and all the methods in the instance will have access to it. so that any instance will be able to read/write data from/to other instances. I tried the following:

class myClass
{
public: static int id; // declaring static variable for use across all instances of this class

  myClass() //constractor
  {
  //here I tried few ways to access and 'id' as static and global variable inside the class:
   id = 0; // compilation (or linker) error: undefined reference to `myClass::id'
   int id = 0; // compilation success, but it does not refer to the static variable.
   static int id = 0; //compilation success, it is static variable that shared among other instances,  but other methods cannot access this variable, so its local and not global.
  }

// example for another function that needs to access the global static variable.
int init_id()
  {
   id++
  }

I tried to search the net, but all the example demonstrates a static variable inside a function or a method, I did not find any static global variable inside a class


Solution

  • You have to define the variable at the top level of a compilation unit (e.g. myClass.cc):

    #include "myClass.h"
    
    int myClass::id = 0;