Skip to content

Static Keyword

Terry Griffin edited this page Nov 12, 2018 · 16 revisions

Static keyword has different meanings when used with different types. We can use static keyword with:

  1. Static Variables : Variables in a function, Variables in a class.
  2. Static Members of Class : Class objects and Functions in a class.

Static Variables in Functions

When you use the static keyword in a function (for example), this tells the compiler to allocate the variable in which static is being applied in a different part of memory. There are three types of memory that "C" uses when running a program.

  1. static: global variable storage, permanent for the entire run of the program.
  2. stack: local variable storage (automatic, continuous memory).
  3. heap: dynamic storage (large pool of memory, not allocated in contiguous order)[2].
Memory Types

When the static keyword is used, the variable is placed in the static portion of memory. All static data is initialized to zero when it is first created (if no other initialization is present).

In the example below, the count variable is placed in "static" memory and is only initialized the first time that countStuff is called. Every subsequent call continues to increment count.

void countStuff() 
{  
    // static variable 
    static int count = 0; 
    cout << count << " "; 
      
    // value is updated and 
    // will be carried to next 
    // function calls 
    count++; 
} 
  
int main() 
{ 
    for (int i=0; i<5; i++){    
        countStuff(); 
    }
    return 0; 
} 

View on Repl.it

Static variables in a class

As we know, static variable are allocated space in the static portion of memory. Therefore static class variables persist throughout every instance created, and are shared by each of the objects. There can not be multiple copies of same static variables for different objects (think about why this is true). Also because of this reason static variables can not be initialized using constructors, because each constructor would "reset" the value of the static variable. Don't get confused with a static variable in a function getting initialized only once. It's not quite the same ... I'll let you think about why.

class myClass 
{ 
   public: 
     static int count;
      
     myClass() 
     { 
       count++;
     }; 
}; 

// Initialize count here because a constructor
// would continuously reset the count to zero.
int myClass::count = 0;

int main() 
{ 
  int r = rand() % 100;
  //or
  cout<<"Enter how many objects you want to create:";
  cin>>r;

  myClass *myArray;

  myArray = new myClass[r];

  // No matter which index we use, they will all print
  // the same value for count.
  cout<<myArray[rand()%r].count;

} 

View on Repl.it

Static Classes

In C++, a "static class" does not mean the same thing that it does in other languages. For example:

In C#: a static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type [3].

It is possible to create a static class in C++, but it doesn't serve the same purpose as in other languages. A good example of a well known static class is the javascript Math class. You do not have to create an instance of the class to access all of its math functionality (e.g. Math.PI, Math.round, Math.sqrt ... etc) [4].

There are no such classes in the C++ standard library, and even though you can technically create a static class in C++, there are more acceptable ways to mimic the behavior of what a static class is supposed to be (grouping together related names without any form of per-object state). One way this can be done is by using namespaces:

namespace Temperature {

    double CelsiusToFahrenheit(double temperatureCelsius){

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (temperatureCelsius * 9 / 5) + 32;

        return fahrenheit;
    }

    double FahrenheitToCelsius(double temperatureFahrenheit)
    {

        // Convert Fahrenheit to Celsius.
        double celsius = (temperatureFahrenheit - 32) * 5 / 9;

        return celsius;
    }
}

// Usage

double F = Temperature::CelsiusToFahrenheit(18.1);
double C = Temperature::FahrenheitToCelsius(99.2);

Just as an interesting example, the code below defines a class, and then declares a static instance. The lifespan of a static variable might not be what you expect:

class statEx 
{ 
    int i; 
    public: 
        statEx() 
        { 
            i = 0; 
            cout << "Inside Constructor\n"; 
        } 
        ~statEx() 
        { 
            cout << "Inside Destructor\n"; 
        } 
}; 
  
int main() 
{ 
    int x = 0; 
    if (x==0) 
    { 
        static statEx obj; 
    } 
    cout << "End of main\n"; 
}

Output:

Inside Constructor
End of main
Inside Destructor

Static Methods in Classes

Just like the static data members or static variables inside the class, static member functions also do not depend on a class instance. Static member functions can be invoked using the object name and the ‘.’ operator (e.g. myObj.sqrt(9)) but it is recommended to invoke the static members using the class name and the scope resolution operator (e.g. math::sqrt(9)).

Static member functions are allowed to access only the static data members or other static member functions, they can not access the non-static data members or member functions of the class.

Source:

  1. https://www.geeksforgeeks.org/static-keyword-cpp/
  2. https://craftofcoding.wordpress.com/2015/12/07/memory-in-c-the-stack-the-heap-and-static/
  3. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
  4. https://www.w3schools.com/js/js_math.asp