What are static mambers within a class..

closed account (9605fSEw)
NOCONTENT
Last edited on
They serve as a sort of data pool shared by all instances of a class. They can be accessed even when on instances of the class exist.
The same applies for static methods.
They can be useful, for example, to know how many instances of a class there are currently in memory.
Those are all very good examples. Just to add to helios's comments:

A common use is to implement the singleton design pattern.
http://www.inquiry.com/techtips/cpp_pro/10min/10min0200.asp

Or to create/dispense unique ID's:
1
2
3
4
5
6
7
8
9
10
class UniqueID
  {
  private:
    static unsigned last_id = 0;  // shared among all instances
    const unsigned id;            // unique to only one instance 

  public:
    UniqueID(): id( ++last_id ) { }
    operator unsigned() const { return id; }
  };


Class count:
1
2
3
4
5
6
7
8
9
10
11
class Fooey
  {
  private:
    static unsigned f_num_instances;

  public:
    Fooey() { f_num_instances++; }
   ~Fooey() { f_num_instances--; }

    unsigned num_instances() const { return f_num_instances; }
  };

Etc.

[typo] "... accessed even when no instances..."
Topic archived. No new replies allowed.