Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

What is Static Keyword in C++

Last Updated on February 16, 2023 by Vikas Chhonkar

In this article, we will be discussing static keyword in C++. The use of static keyword in C++ is not limited to just the scope of variables as in C language where they are used to bypass the restriction of usage in their own scope making another ways possible. In static keyword C++ uses includes static members of a class such as objects and functions within the class.

Static Keyword has its use in C as well as its successor C++ with slightly new features to it in the Object-oriented programming language. In C, the use of static keyword is limited to declaring or initializing variables which is not the case with use of static keyword in C++ as we will discuss further in this article what more they offer in C++.

Static Variable

Usage of static keyword C++ in general is performed for a static variable as the moment it is declared, space is allocated to the variable for its lifetime and multiple calls to the function don’t make reassignment of the variable as it carried throughout the lifetime of the program.

Usage in function

The usage can be performed in the function while the presence of variable can be independent of life of the function as it can be used even after the function has completed its set of instructions after being called.

#include <iostream>
#include <string>
using namespace std;
  
void foo(){ 
    static int ctr = 0;
    cout << ctr << endl;
    ctr++;
}
int main(){
    for (int i=0; i<5; i++)    
        foo();
    return 0; 
}

Output :

0
1
2
3
4

The following snippet of code denotes one of essential use of static keyword in C++ as the function was called consecutively for five times but no value was passed despite that the ctr variable was not reinitialized to value of 0 instead kept on incrementing the very first moment it was set up and allocated the space.

Usage in class

The only difference between use of static keyword in C++ in function and class is that while using them in class, the context changes from functions to objects where a static variable declared inside a class can be used between various objects once initialized without reinitializing while during creation of new objects.

It sets up the variable as default in the class they are being used in. However, to avoid them being reinitialized and cause error, they cannot be passed to constructors on creation of object using static keyword in C++.

#include<iostream>
using namespace std;
  
class PrepBytes
{
public:
    static int i;
      
    PrepBytes(){
    };
};
  
int PrepBytes::i = 12;
  
int main(){
    PrepBytes att;
    PrepBytes att2;
    cout << att.i <<" " <<att2.i; 
}

Output

 12 12

In the above example, the att and att2, both objects are initialized with both of them having value of I set up as 12 earlier. The value will remain constant across objects with its use throughout the use of static keyword in C++ class.

Static Member

It expresses the use of static keyword in Object Oriented Programming to increase the transparency of objects or class function wherein the life of objects is equated to program and function can be called without the dependency of an actual object.

Static Objects of Class

In a manner similar to declaration of static variable, class objects can also be declared as static where they tend to exist in the program till it remains in the state of execution.

Taking an example, it might be easier for you to understand on how state members actually work as constructor and destructors show ambiguous behavior when the object is set up as static which will be active till the lifetime of its parent program.

#include <iostream>
using namespace std;
class PrepBytes{
    int a;
    public:
        PrepBytes(){
            cout << "Hello From PrepBytes" <<endl;
        }
        ~PrepBytes(){
            cout << "Hello To PrepBytes" <<endl;
        }  
};
int main()
{
    if (true){
    PrepBytes att;
    }
    cout << "Hello World" <<endl;
    return 0;
}

Output:

Hello From PrepBytes
Hello To PrepBytes
Hello World

In the above program we get the answer where Hello world i.e the text inside our main body is printed after the execution of constructor and destructor when control returns back to the main function. However this can be tweaked to print the Hello World text first and the text inside the destructor at the end by of use of static keyword in C++’s object declaration.

#include <iostream>
using namespace std;
class PrepBytes{
    int a;
    public:
        PrepBytes(){
            cout << "Hello From PrepBytes" <<endl;
        }
        ~PrepBytes(){
            cout << "Hello To PrepBytes" <<endl;
        }  
};
int main()
{
    if (true){
    static PrepBytes att;
    }
    cout << "Hello World" <<endl;
    return 0;
}

Output:

Hello From PrepBytes
Hello World
Hello To PrepBytes

The destructor was executed after the program was terminated. Therefore, stating that class objects are static in nature. Hence static keyword C++ is used to bar delay the destructor until the end of the program.

Static Functions of Class:

The functions lying inside the class can be made static where they can be called without the presence of an object. The only way they can be called from the main function with the use of static keyword in C++ is by placing the class name and scope resolution operator before calling the static function which is actually lying inside the class.

#include <iostream>
#include <string>
using namespace std;
class PrepBytes{
    public:
    static void Hello(){
        cout << "This is PrepBytes" <<endl;
    }
};
int main(){
    PrepBytes::Hello();
}

Conclusion

Now that it is clear static keyword in C++ is used to declare a variable that has its lifetime joined with the program in function and class, as well as the use of static keyword in C++, extends to statics members such as objects and functions. Application of static keyword in C++ is extensively used for modification of program is avoided as in the aftermath of initialization, any redundant operation of the variable is avoided.

This brings us to the end of Static Keyword in C++. Hope you have a better understanding of the topic now. You can check out more articles on PrepBytes.

Frequently Asked Questions Related to Static Keyword in C++:-

1. What is the use of static keywords in C++?
Ans. Modification of variables cannot be done after placing static before a variable or an object. Static keyword C++ is useful in case we want to allocate the memory for the lifetime of the program.

2. What are the differences between local and static variables?

Local Variable Static Variable
Declared inside the function Declared inside as well outside the function
Default value is set as the garbage Default value is set as zero

3. How are static functions accessed with using static keyword in C++?
Ans. The scope resolution operator is used to access or call the function without even initializing the object for a function that lies inside a class. Scope Resolution operator is denoted by ‘::’.

4. What is the lifetime of a static variable?
Ans. Static Variable’s lifetime remains permanent and they continue to exist in the program. They are stored in static memory.

You can also checkout the following articles on C++:

  1. OOPS Concepts in C++ with Examples
  2. What is Member Function in C++?
  3. Access Specifiers In C++ – A Quick glimpse to private, public, and protected

Leave a Reply

Your email address will not be published. Required fields are marked *