The Wayback Machine - https://web.archive.org/web/20240907055858/https://www.geeksforgeeks.org/static-keyword-cpp/
Open In App

Static Keyword in C++

Last Updated : 16 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Static variables in C

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

  1. Static Variables: Variables in a function, Variables in a class
  2. Static Members of Class: Class objects and Functions in a class Let us now look at each one of these uses of static in detail.

Static Variables

Static variables in a Function: When a variable is declared as static, space for it gets allocated for the lifetime of 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. This is useful for implementing coroutines in C/C++ or any other application where the previous state of function needs to be stored. 

C++




// C++ program to demonstrate
// the use of static Static
// variables in a Function
#include <iostream>
#include <string>
using namespace std;
 
void demo()
{
    // 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++)
        demo();
    return 0;
}


Output

0 1 2 3 4 

You can see in the above program that the variable count is declared static. So, its value is carried through the function calls. The variable count is not getting initialized every time the function is called. As a side note, Java doesn’t allow static local variables in functions.

Static variables in a class: As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of the same static variables for different objects. Also because of this reason static variables can not be initialized using constructors. 

C++




// C++ program to demonstrate static
// variables inside a class
 
#include <iostream>
using namespace std;
 
class GfG {
public:
    static int i;
 
    GfG(){
        // Do nothing
    };
};
 
int main()
{
    GfG obj1;
    GfG obj2;
    obj1.i = 2;
    obj2.i = 3;
 
    // prints value of i
    cout << obj1.i << " " << obj2.i;
}


Output

undefined reference to `GfG::i'
collect2: error: ld returned 1 exit status

You can see in the above program that we have tried to create multiple copies of the static variable i for multiple objects. But this didn’t happen. So, a static variable inside a class should be initialized explicitly by the user using the class name and scope resolution operator outside the class as shown below: 

C++




// C++ program to demonstrate static
// variables inside a class
 
#include <iostream>
using namespace std;
 
class GfG {
public:
    static int i;
 
    GfG(){
        // Do nothing
    };
};
 
int GfG::i = 1;
 
int main()
{
    GfG obj;
    // prints value of i
    cout << obj.i;
}


Output

1

Static Members of Class

Class objects as static: Just like variables, objects also when declared as static have a scope till the lifetime of the program. Consider the below program where the object is non-static. 

C++




// CPP program to illustrate
// when not using static keyword
#include <iostream>
using namespace std;
 
class GfG {
    int i;
 
public:
    GfG()
    {
        i = 0;
        cout << "Inside Constructor\n";
    }
    ~GfG() { cout << "Inside Destructor\n"; }
};
 
int main()
{
    int x = 0;
    if (x == 0) {
        GfG obj;
    }
    cout << "End of main\n";
}


Output

Inside Constructor
Inside Destructor
End of main

In the above program, the object is declared inside the if block as non-static. So, the scope of a variable is inside the if block only. So when the object is created the constructor is invoked and soon as the control of if block gets over the destructor is invoked as the scope of the object is inside the if block only where it is declared. Let us now see the change in output if we declare the object as static. 

C++




// CPP program to illustrate
// class objects as static
#include <iostream>
using namespace std;
 
class GfG {
    int i = 0;
 
public:
    GfG()
    {
        i = 0;
        cout << "Inside Constructor\n";
    }
 
    ~GfG() { cout << "Inside Destructor\n"; }
};
 
int main()
{
    int x = 0;
    if (x == 0) {
        static GfG obj;
    }
    cout << "End of main\n";
}


Output

Inside Constructor
End of main
Inside Destructor

You can clearly see the change in output. Now the destructor is invoked after the end of the main. This happened because the scope of static objects is throughout the lifetime of the program.

Static functions in a class: Just like the static data members or static variables inside the class, static member functions also do not depend on the object of the class. We are allowed to invoke a static member function using the object and the ‘.’ operator but it is recommended to invoke the static members using the class name and the scope resolution operator. 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. 

C++




// C++ program to demonstrate static
// member function in a class
#include <iostream>
using namespace std;
 
class GfG {
public:
    // static member function
    static void printMsg() { cout << "Welcome to GfG!"; }
};
 
// main function
int main()
{
    // invoking a static member function
    GfG::printMsg();
}


Output

Welcome to GfG!

Related Articles:



Previous Article
Next Article

Similar Reads

Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Use of explicit keyword in C++
Explicit Keyword in C++ is used to mark constructors to not implicitly convert types in C++. It is optional for constructors that take exactly one argument and work on constructors(with a single argument) since those are the only constructors that can be used in typecasting. Let's understand explicit keyword through an example. Predict the output o
3 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
C++ mutable keyword
The mutable storage class specifier in C++ (or use of mutable keyword in C++) auto, register, static and extern are the storage class specifiers in C. typedef is also considered as a storage class specifier in C. C++ also supports all these storage class specifiers. In addition to this C++, adds one important storage class specifier whose name is m
4 min read
Using Keyword in C++ STL
The using keyword in C++ is a tool that allows developers to specify the use of a particular namespace. This is especially useful when working with large codebases or libraries where there may be many different namespaces in use. The using keyword can be used to specify the use of a single namespace, or multiple namespaces can be listed using the u
6 min read
Static Objects in C++
Prerequisite: Static Keyword in C++ An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory. C++ supports two types of static objects: Local Static ObjectsGlobal Static Object
3 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
“static const” vs “#define” vs “enum”
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier). Static : determines the lifetime and visibility
4 min read
Memory Allocation in Static Data Members in C++
C++ allows defining static data members within a class using the static keyword. When a data member is declared as static, then we must keep the following note in mind: Irrespective of the number of objects created, only a single copy of the static member is created in memory. All objects of a class share the static member. All static data members
4 min read
Difference between Static and Friend Function in C++
Static Function: It is basically a member function that can be called even when the object of the class is not initialized. These functions are associated with any object and are used to maintain a single copy of the class member function across different objects of the class. This function is denoted by using the static keyword. Friend Function: I
3 min read
Static Member Function in C++
The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with the objects of the class. Just like a static variab
4 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Templates and Static variables in C++
Function templates and static variables: Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; void fu
2 min read
Some interesting facts about static member functions in C++
1) static member functions do not have this pointer. For example following program fails in compilation with error "`this' is unavailable for static member functions " C/C++ Code #include&lt;iostream&gt; class Test { static Test * fun() { return this; // compiler error } }; int main() { getchar(); return 0; } 2) A static member function cannot be v
1 min read
Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
C++ Static Data Members
Static data members are class members that are declared using static keywords. A static member has certain special characteristics which are as follows: Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.It is initialized before any object of this class
5 min read
How to Initialize a Static std::map&lt;int, int&gt; in C++
In C++, std::map&lt;int, int&gt; is a commonly used container that stores key-value pairs. There are scenarios where we may want to initialize a static std::map with predefined key-value pairs that remain constant throughout the program's execution. In this article, we will learn different methods to initialize a static std::map&lt;int, int&gt; in
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :