Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) static

 

Keyword enabling in-class or in-function static variables or create static member function.

 

A common use of static is when you want to keep track of how many instances a class has:

 

#include <iostream>

class InstanceCounter
{
  static int mNinstances;
  
  public:
  InstanceCounter()
  {
    ++mNinstances;
    std::cout << "Constructed an instance."
      << "Now there are " << mNinstances << "." << std::endl;
  }
  ~InstanceCounter()
  {
    --mNinstances;
    std::cout << "Destructed an instance."
      << "Now there are " << mNinstances << "." << std::endl;
  }
};

int InstanceCounter::mNinstances = 0;

int main()
{
  InstanceCounter one, two, three, four,five;
}

 

 

 

 

 

Advice

 

 

 

 

 

 

Notes to self

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict