Class Variable - RJAE5/2143-OOP GitHub Wiki

Class Variable(s)

When creating attributes in a class, using the static keyword before them makes what is known as a class variable. These special variables are stored specifically in the static portion of memory, and subsequently persist throughout every instance of the class. Typically, each instance of a class is thought to have its own set of attributes, but a class variable is a single value shared by all instances for that specific attribute and can therefore be changed by any one instance for all other instances.

Example

class myClass 
{ 
   public: 
     static int count;
      
     myClass() 
     { 
       count++;
     }; 
}; 

// Initialize count here because a constructor
// would continuously reset the count to zero.
int myClass::count = 0;

int main() 
{ 
  int r = rand() % 100;
  //or
  cout<<"Enter how many objects you want to create:";
  cin>>r;

  myClass *myArray;

  myArray = new myClass[r];

  // No matter which index we use, they will all print
  // the same value for count.
  cout<<myArray[rand()%r].count;

} 

Code from https://github.com/rugbyprof/2143-Object-Oriented-Programming/wiki/Static-Keyword

Important Notes

  • Static class variables only exist once, no matter how many instances of the class there are
  • Each instance shares this single copy, and if it is manipulated, it is changed for all instances globally

Sources:

  1. https://www.geeksforgeeks.org/static-keyword-cpp/
  2. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members