1

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

orenk
  • 109
  • 1
  • 2
  • 12
  • 1
    It's not enough to delcare static variables, you also need to define them somewhere. There is a duplicate for this, I'm sure. In short: add the definition `int myClass::id = 0` to some cpp-file – Lukas-T Feb 27 '20 at 11:13
  • please next time include the error in your question when the question is about a compiler error – 463035818_is_not_an_ai Feb 27 '20 at 11:17

1 Answers1

1

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;
Alnitak
  • 334,560
  • 70
  • 407
  • 495