FAQ 16.03 What is an analogy for static data members?

Static data members are like data located in the factory rather than in the objects produced by the factory.

In Detroit, there's a big sign with a running total of the number of cars produced during the current year. But that information isn't under the hood of any given car; all the car knows is a serial number indicating its ordinal number. The total number of cars produced is therefore factory data.

In the following example, class Car is the factory that is used to produce Car objects. Every car has a serial number (serial_). The factory keeps count of the number of cars that have been built via num_, which is a class (or static) datum; serial_ is an object (or instance) datum. The constructors of class Car are responsible for incrementing the number of cars that have been built; for simplicity this number is used as the serial number.

 #include <iostream> using namespace std; class Car { public:   Car() throw();                                     <-- 1   Car(const Car& c) throw();                         <-- 2   // No need for an explicit assignment operator or destructor   // since these don't create new Car objects (but see FAQ 30.06).   static int num_;                                   <-- 3 private:   int serial_;                                       <-- 4 }; Car::Car() throw() : serial_(num_) {   cout << "Car ctor\n";   ++num_; } Car::Car(const Car& c) throw() : serial_(num_) {   cout << "Car copy\n";   ++num_; } int Car::num_ = 0;                                   <-- 5 

(1) Increments Car::num_

(2) Increments Car::num_

(3) Class data

(4) Object data

(5) Class data is automatically initialized, often before main()

Just as a factory exists before it produces its first object, class (static) data can be accessed before the first object is instantiated as well as after the last object has been destroyed.

 int main() {   cout << "Car::num_ = " << Car::num_ << '\n';   {     Car a;     cout << "Car::num_ = " << Car::num_ << '\n';     Car b;     cout << "Car::num_ = " << Car::num_ << '\n';     Car c = a;     cout << "Car::num_ = " << Car::num_ << '\n';   }   cout << "Car::num_ = " << Car::num_ << '\n'; } 

The output is

 Car::num_ = 0 Car ctor Car::num_ = 1 Car ctor Car::num_ = 2 Car copy Car::num_ = 3 Car::num_ = 3 

Note: See the next FAQ regarding inline functions that access static data members.



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