FAQ 16.02 What are static class members?

Static class members are data and functions that are associated with the class itself, rather than with the objects of the class.

In the following example, class Fred has a static data member x_ and an instance data member y_. There is only one copy of Fred::x_ regardless of how many Fred objects are created (including no Fred objects), but there is one y_ per Fred object. Thus x_ is said to be associated with the class and y_ is said to be associated with an individual object of the class. Similarly class Fred has a static member function f() and an instance member function g().

 class Fred { public:   static void f() throw();                           <-- 1   void g() throw();                                  <-- 2 protected:   static int x_;                                     <-- 3   int y_;                                            <-- 4 }; 

(1) Member function associated with the class

(2) Member function associated with an individual object of the class

(3) Data member associated with the class

(4) Data member associated with an individual object of the class

Everything except instance data members must be defined somewhere, such as in the Fred.cpp source file:

 #include "Fred.hpp" void Fred::f() throw()                               <-- 1 { /*...*/ } void Fred::g() throw() { /*...*/ } int Fred::x_ = 3;                                    <-- 2 

(1) The static keyword is not used at the function's definition

(2) Static data members must be explicitly defined in exactly one source file

Static data members are often referred to as class data, and static member functions are often referred to as class services or class methods.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net