CIS 22 - Data Structures: Static Class Members


    A variable that is part of a class, yet is not part of an object of that class, is called static member. There is exactly one copy of a static member instead of one copy per object, as for ordinary non-static members. Similarly, a function that needs access to members of a class, yet does not need to be invoked for a particular object, is called a static member function.

1. Static Member Data.
2. Static Functions.
3. Example.
 

1. Static Member Data.

There are two types of data members used in classes:
1) instance data, meaning that one copy of the data exists for each instance of an object that is created.
    In other words, instance data is associated with a particular subject.
2) static data that applies to the class as a whole, rather than to particular objects.
    One copy of such data exists for the entire class.

    Syntax:
You must have separate statements to declare a variable within a class and to define it outside of the class.

    Example:
    class Example {
        private:
            static int stavar;            // declaration
        ...
    }
 
    int Example::stavar = 77;    // definition
 
  



2. Static Functions.
 
Static function, like static data, applies to an entire class rather than a particular object. A static function can not refer to any nonstatic member data in its class, because static functions do not know anything about objects in a class. All they can access is static, class-specific data. You can call a static function even before you have created any objects of a class.

    Syntax:
Function calls to static functions are made without referring to a particular object. Instead, the function is defined by connecting it to the class name with the scope resolution operator.

     Example:
    class Example {
        private:
            ...
        public:
            static int stafunc()        // function definition
            {
                    // can access only static member data
            }
    };
 
    main() {
        ...
        Example::stafunc();            // function call
        ...
    }
 



3. Example.
 
The program creates a class widgets (small devices of obscure purpose). Each widget is given a serial number, starting with 10,000. The class uses a static variable to keep track of how many widgets have been created so far. It uses this total to generate a serial number and to place it in the instance variable when a new widget is created.

Michael Gorenburg - Spring '98


Back to CIS 22 home page