Last modified on 25 July 2010, at 08:28

C++ Programming

static member functionEdit

Member functions or variables declared static are shared between all instances of an object type. Meaning that only one copy of the member function or variable does exists for any object type.

member functions callable without an object

When used in a class function member, the function does not take an instantiation as an implicit this parameter, instead behaving like a free function. This means that static class functions can be called without creating instances of the class:

class Foo {
public:
  Foo() {
    ++numFoos;
    cout << "We have now created " << numFoos << " instances of the Foo class\n";
  }
  static int getNumFoos() {
    return numFoos;
  }
private:
  static int numFoos;
};
 
int Foo::numFoos = 0;  // allocate memory for numFoos, and initialize it
 
int main() {
  Foo f1;
  Foo f2;
  Foo f3;
  cout << "So far, we've made " << Foo::getNumFoos() << " instances of the Foo class\n";
}
Named constructorsEdit

Named constructors are a good example of using static member functions. Named constructors is the name given to functions used to create an object of a class without (directly) using its constructors. This might be used for the following:

  1. To circumvent the restriction that constructors can be overloaded only if their signatures differ.
  2. Making the class non-inheritable by making the constructors private.
  3. Preventing stack allocation by making constructors private

Declare a static member function that uses a private constructor to create the object and return it. (It could also return a pointer or a reference but this complication seems useless, and turns this into the factory pattern rather than a conventional named constructor.)

Here's an example for a class that stores a temperature that can be specified in any of the different temperature scales.

class Temperature
{
    public:
        static Temperature Fahrenheit (double f);
        static Temperature Celsius (double c);
        static Temperature Kelvin (double k);
    private:
        Temperature (double temp);
        double _temp;
};
 
Temperature::Temperature (double temp):_temp (temp) {}
 
Temperature Temperature::Fahrenheit (double f)
{
    return Temperature ((f + 459.67) / 1.8);
}
 
Temperature Temperature::Celsius (double c)
{
    return Temperature (c + 273.15);
}
 
Temperature Temperature::Kelvin (double k)
{
    return Temperature (k);
}