Everything we’ve looked at so far is what is known as an instance member. That is, each instance of a class – called and object, has it’s own set of properties and methods. This is mostly what is done.
So if we look at two Circle objects for example, the radius of one circle is totally independent of another circle object. This is what we normally want.
But what if we wanted to share data between all instances. For example, a counter to see how many were created. Sure we could manually try to keep track, but if we had a complex program, that could be hard as who knows where the instance would be created.
That’s why we have static properties and methods. A static method or property is shared between all instances.
And like how with a static variable in a function, it remembers the value, so does a static class member. In fact, it’s created the same way, by putting static before the data type, or the return type of a method.
Rules for working with Static Members
There are some rules when working with static members however.
A static property can be used in any method, however a static method can only use static properties and local properties.
Static properties are automatically initialized to zero if they are numeric.
// up with the variables
static int countOfObjects;
// down with the method declarations
static int getObjectCount();
By default in C++ the static property should be set to 0 (zero). However, Visual Studio still wants you to set it implicitly, like you see below.
int Circle::countOfObjects{ 0 };
Notice that you need to define your class scope so that it knows which class it belongs to.
Instance and Static Members was originally found on Access 2 Learn