In C++, a static data member works as a pseudo global variable between all instances of a class. In other words, it creates a variable that is the same for all members of a class.

For Example:

#include <iostream>

class test
{
public:
static int experiment;
};

test test::experiment; //Must be initialized outside class to exist

int main()
{
test bob;
test george;
bob.experiment = 5;
cout << bob.experiment << endl << george.experiment;
return 0;
}

The code results in the following output:

5
5

As you can clearly see, the change made in the "bob" instance of the test class was also reflected in the "george" instance of the test class.

Also, if the static variable is public, then you can do this:

test::experiment = 5;

This lets you change the static variable without referencing any specific instance of the class. Possible applications for static data members include a memory pool for overloading the new and delete operators, or saving some memory by using this pseudo global variable instead of a plain 'ol global variable.

Log in or register to write something here or to contact authors.