Static Members Function In Cpp
Static members:
A class can contain static members, either data or functions.
Static data members of a class are also known as “class variables”, because there is only one unique value for all the objects of that same class. Their content is not different from one object of this class to another.
For example, it may be used for a variable within a class that can contain a counter with the number of objects of that class that are currently allocated, as in the following example:
CODE/PROGRAM/EXAMPLE
//static members in classes
#include <iostream>
using namespace std;
class CDummy {
public:
static int n;
CDummy () { n++; };
~CDummy () { n--; };
};
int CDummy::n=0;
int main () {
CDummy a;
CDummy b[5];
CDummy * c = new CDummy;
cout << a.n << endl;
delete c;
cout << CDummy::n << endl;
return 0;
}
O/P : 7
6
In fact, static members have the same properties as global variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization).
In order to initialize a static data-member we must include a formal definition outside the class, in the global scope, as in the previous example:
Because it is a unique variable value for all the objects of the same class, it can be referred to as a member of any object of that class or even directly by the class name (of course this is only valid for static members):
CODE/PROGRAM/EXAMPLE
cout << a.n;
cout << CDummy::n;
These two calls included in the previous example are referring to the same variable: the static variable n within class CDummy shared by all objects of this class.
Once again, I remind you that in fact it is a global variable. The only difference is its name and possible access restrictions outside its class.
Just as we may include static data within a class, we can also include static functions. They represent the same: they are global functions that are called as if they were object members of a given class.
They can only refer to static data, in no case to non-static members of the class, as well as they do not allow the use of the keyword this, since it makes reference to an object pointer and these functions in fact are not members of any object but direct members of the class.