Static Keyword in C++

Static keywords in C++

On this page we will discuss about static keyword in C++ . Static keywords is used for Common space technique and sometimes scope modification in a C++ program.
Static Keyword in C++ img

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

Static Keyword in C++ Classes

Basic Properties of Static data members

1. Static data members are initialized with zero automatically

Run

#include 
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)

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription