C++ Static Data Members
C++ Static Data Members
Syntax
className {
static data_type data_member_name;
.....
}
#include <iostream>
using namespace std;
// class definition
class A {
public:
// static data member here
static int x;
A() { cout << "A's constructor called " << endl; }
};
// Driver code
int main()
{
// accessing the static data member using scope
// resultion operator
cout << "Accessing static data member: " << A::x
<< endl;
return 0;
}
Defining Static Data Member:
As told earlier, the static members are only declared in the class
declaration. If we try to access the static data member without an explicit
definition, the compiler will give an error.
To access the static data member of any class we have to define it first
and static data members are defined outside the class definition. The only
exception to this are static const data members of integral type which can
be initialized in the class declaration.
Syntax
datatype class_name::var_name = value...;
For example, in the above program, we have initialized the static data
member using the following statement:
int A::x = 10