4.1 static data member

Let us consider the following example:

class X
{
    static int serialno;
  public:
    X(void);
};

int X::serialno = 0;

X::X(void)
{
  serialno++;
  cout << "the constructor has been invoked " << serialno << " times." << endl;
}

This rather useless constructor illustrates one important point: it is possible to use a static data member to keep track of states that should be shared by all objects of the same class. In many ways, X::serialno is like a global variable, but its scope is limited to the methods of X because it is in the private section.

Note that a static data member of a class, if declared public, must be accessed in the context of the class, and not of an object. In other words, if serialno were in the public section, it can only be accessed as X::serialno, but not myX.serialno, given that myX is an object of class X.



Copyright © 2006-09-19 by Tak Auyeung