Static Data Members

Static data members of global classes have external linkage and can be initialized in file scope like other global objects. Static data members follow the usual class access rules, except that they can be initialized in file scope. Static data members and their initializers can access other static private and protected members of their class. The initializer for a static data member is in the scope of the class declaring the member.

The following example shows how you can initialize static members using other static members, even though these members are private:

class C {
      static int i;
      static int j;
      static int k;
      static int l;
      static int m;
      static int n;
      static int p;
      static int q;
      static int r;
      static int s;
      static int f() { return 0; }
      int a;
public:
      C() { a = 0; }
      };


C c;
int C::i = C::f();    // initialize with static member function
int C::j = C::i;      // initialize with another static data member
int C::k = c.f();     // initialize with member function from an object
int C::l = c.j;       // initialize with data member from an object
int C::s = c.a;       // initialize with nonstatic data member
int C::r = 1;         // initialize with a constant value


class Y : private C {} y;

int C::m = Y::f();
int C::n = Y::r;
int C::p = y.r;       // error
int C::q = y.f();     // error

The initializations of C::p and C::x cause errors because y is an object of a class that is derived privately from C, and its members are not accessible to members of C.

You can only have one definition of a static member in a program. If a static data member is not initialized, it is assigned a zero default value. Local classes cannot have static data members.



Using the Class Access Operators with Static Members
Example of Static Data Members
Example of Static Data Members in Templates


File Scope
Static Member Functions
Static Members
Member Access
Local Classes