Categories: C++

static keyword in C++

When the static keyword is used, variable or data members or functions can no longer be changed. It is allocated for the lifetime of the program.

The static keyword can be used with:

  • Static Variables: Variables in a function, Variables in a class
  • Static Members of Class: Class objects and Functions in a class
Static Variables in a function:

When a variable is declared static, space is reserved for it for the duration of the program. Even if the function is called several times, space for the static variable is allocated once only, and the value of the variable in the previous call is carried over to the next function call.

Example:

#include <iostream>
#include <string>
using namespace std;

void func()
{
 // static variable
 static int count = 0;
 cout << count << " ";
 count++;
}

int main()
{
 for (int i=0; i<5; i++) 
  func();
 return 0;
}
Output:
0 1 2 3 4 
Static Variables in a class:

static variables are only initialized once because they are allocated space in separate static storage, the static variables in a class are shared by the objects. Multiple copies of the same static variable for different objects are not permitted. As a result, static variables cannot be initialized using constructors.

Example:

#include<iostream>
using namespace std;

class Student
{
public:
 static int i;
 
 Student()
 {
  // Do nothing
 };
};
int Student:: i=9;
int main()
{
   Student obj1;
 
   // prints value of i
    cout << obj1.i;
    return 0;
}
Output:
9

If we had tried to initialize the static variable ‘i’ after creating the object of the class then it would have returned an error message.

Class objects as static:

Objects, like variables, have a scope that lasts the duration of the program when declared as static.

Example:
// CPP program to illustrate
// class objects as static
#include<iostream>
using namespace std;

class Coderz
{
 int i = 0;
 
 public:
 Coderz()
 {
  i = 0;
  cout << "Inside Constructor\n";
 }
 
 ~Coderz()
 {
  cout << "Inside Destructor\n";
 }
};

int main()
{
 int x = 0;
 if (x==0)
 {
  static Coderz obj;
 }
 cout << "End of main\n";
}
Output:
Inside Constructor
End of main
Inside Destructor

Following the completion of the main, the destructor is called. This occurred because the scope of a static object extends throughout the program’s lifetime.

Static functions in a class:

Static member functions, like static data members or static variables within the class, do not rely on the class’s object. We can call a static member function with the object and the ‘.’ operator, but it is preferable to call static members with the class name and the scope resolution operator.

Note: Static member functions can only access static data members or other static member functions.

Example:

#include<iostream>
using namespace std;

class Coderz
{
public:
 
 // static member function
 static void fact(int n)
 {  int nn=1;
     for(int i=n;i>=1;i--)
     {
         nn=nn*i;
  
        }
 cout<<nn;
 }
};

// main function
int main()
{
 // invoking a static member function
 Coderz::fact(5);
}
Output:
120

Note: also read about Constructors and Destructors in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago