Static Keyword in C++

Static in C++​

Static keywords in C++ is used for Common space technique and sometimes scope modification in a C++ program.

Static can be used in the following contexts –

  1. Static data members (Variables)
    1. Inside a function
    2. Inside a class
  2. Static Objects of a class
  3. Static member functions

Topics Discussed

We will discuss the following topics in the post –

  • Static Data Members in a Function
  • Static Data Members in Classes
  • Basic Properties of Static Data Members
  • Static Member Function
  • Static objects

Static Data Members (Variables)

Inside a function

The static variable (data member), has a lifetime throughout the program. 

Even if the function is called multiple times, space for the static variable is allocated only once and the value of the variable in the previous call gets carried through the next function call.

Static Keyword in c++

Example

Here we have created a static variable count inside a function, value is carried over in every function call

Run
#include <iostream> 
using namespace std; 
  
void myFunction() 
{  
    // static variable, 
    // will only get initialised in first function call
    static int count = 0; 
    
    cout << count << " "; 
      
    // value from previous function call is retained 
    // will be carried to next function calls
    count++; 
} 
  
int main() 
{ 
    for (int i = 0; i <= 10; i++)     
        myFunction();
        
    return 0; 
}

Output

0 1 2 3 4 5 6 7 8 9 10

Inside a class

Generally, separate copies & memories of variables (data members) are created for each object for any given class.

However, when a variable (data member) is declared as static only a single copy of memory is created for all the objects & each object shares the same copy for the static variable.

Note – Static data members are class members, not object member

Example Program

Run
#include <iostream>
using namespace std;

class test
{ 
  public:
    // static int count = 1;
    // the above will give error
    // static member definition(initialization) must be outside the class
    
    // static member definiton only
    static int count;
    
    test(){
        // static members of a class can't be initialised 
        // in a constructor as they are not associated 
        // with each object of the class. It is shared by all objects.
    }
};

// static data members definition must be outside the class
int test::count = 1;

int main()
{
    // count is 1 now after object creation
    test obj1, obj2;

    cout << "obj1.count :" << obj1.count << endl;
    cout << "obj2.count :" << obj2.count << endl;

    // obj1.count, obj2.count both become 2 as static member
    obj1.count = 2;

    cout << "\n\nobj1.count :" << obj1.count << endl;
    cout << "obj2.count :" << obj2.count << endl;
    
    return 0;
}/pre>
  • Change in obj1.count will also reflect on the change in obj2.count
  • Since both share the same static count variable
  • As ‘count’ is static, only a single copy is shared by all objects hence change in any object will have a change in all other objects.

Basic Properties of Static data members

1. Static data members are initialized with zero automatically

Run
#include <iostream>
using namespace std;

class Test
{
    public:
    static int count; // static data member declaration
};

// not defining(initializing) but making accessible
int Test::count;

int main()
{
    Test t1;
    
    cout << "Value of static member = " << t1.count << endl;
    
    return 0;
}

Output

Value of static member = 0

2. Static data members can be called directly using the class name

Run
#include <iostream>
using namespace std;

class Test
{
    public:
    static int count; // static data member declaration
};

// not defining(initializing) but making accessible
int Test::count;

int main()
{
    //object not created like test t1, t2

    //static members can be accessed without created object
    //just use name_Of_Class::variable_name
    //if not declared static member's data value will be 0 by default
    cout << "Value of static member = " << Test::count << endl;
    
    return 0;
}

Output

Value of static member = 0

Static Member functions

Definition: A static member function is designed only for accessing static data members, other static member functions and any other functions from outside the class.

  • A static member function can be called even if no objects of the class exist
  • Static member functions have a class scope and do not have access to this pointer of the class.
  • The static function can only access static members of the class

Example Program

Run
/*Program to demonstrate static member functions*/

#include <iostream>
using namespace std;

class sampleClass
{
  public:
    // static data members
    static int a,b;

    // non static data member
    int c;

    // static function definition
    // will only work with static data members
    static void add()
    {
        // static function can only access static data members
        cout << "Enter a, b values: ";
        cin >> a >> b;
        cout << "a + b = " << a + b;

        // following will give error -
        // error:cannot access non static data 'c' in static function
        // cin >> c;
    }
};

// both values will become 0 by default
int sampleClass::a;
int sampleClass::b;

int main()
{
  // calling static function with out object
  sampleClass::add();
  
  return 0;
}

Output

Enter a, b values: 10 20
a + b = 30

Static Objects

Very similar to static variables whose scope becomes till the lifetime of the program.

Similarly, for static objects, their scope becomes till just before the program terminates.

We can verify this with the following two programs below –

  • Example 1: Without a static object
  • Example 2: With a Static object

Example 1

Constructors/Destructor functioning without static objects

  • When the object is not static, the object is destroyed as soon as its scope ends.
  • In the example below destructor is called as soon as the scope of the object ends
  • Signalling object being destroyed as soon as scope ended
Run
#include <iostream>
using namespace std;

class PrepInsta 
{ 
    public:
    // constructor
    PrepInsta() { 
        cout << "PrepInsta Constructed\n"; 
    } 
    
    // destructor
    ~PrepInsta() { 
        cout << "PrepInsta Destructed\n"; 
    } 
}; 

int main() 
{
    if(1) {
        // scope of obj starts here (Constructor called)
        PrepInsta obj; 

    }
    // scope of obj ends here (Destructor Called)
    // since the object was not static

    cout << "End of main function\n"; 
}

Output

PrepInsta Constructed
PrepInsta Destructed
End of main function

Example 2

Constructors/Destructors functioning with static objects

  • When the object is static, the object is destroyed only when the program ends
  • In the example below destructor is called just before program terminates
Run
#include <iostream>
using namespace std;

class PrepInsta 
{ 
    public:
    // constructor
    PrepInsta() { 
        cout << "PrepInsta Constructed\n"; 
    } 
    
    // destructor
    ~PrepInsta() { 
        cout << "PrepInsta Destructed\n"; 
    } 
}; 

int main() 
{
    if(1) {
        // scope of obj starts here (Constructor called)
        static PrepInsta obj; 

    }

    cout << "End of main function\n"; 
    
    // scope of obj ends here (Destructor Called)
    // just before the program terminates
    // since the object was static
}

Output

PrepInsta Constructed
End of main function
PrepInsta Destructed

Facts about static members / methods

  • Static data members can be accessed by other methods too
  • Overloading static methods is possible
  • Non-static data members can not be accessed by static methods.
  • Static methods can only access static members (data and methods)