What is the Static Keyword in C++?

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Variables declared globally in C++ (outside any function) remain until the entire program finishes executing. They are said to have a static memory space allotted to them, which means they are initialized only once during the program, and their memory is deallocated only when the program finishes its execution. This privilege is not enjoyed by variables declared inside functions. This is where the static keyword is useful in C++. It helps provide all of these qualities to variables declared inside functions. And not only variables but the static keyword in C++ can be used with variables, functions as well as class objects.

As the meaning suggests, the static keyword tells the compiler that this variable must remain throughout the program. This means that the variable is initialized only once and is not deallocated until the termination of the complete program.

This is very useful when we want the variables in a function to not be reinitialized every time the function terminates and is called again. Declaring the variable with the static keyword ensures that it maintains its memory space throughout the program. Let us look at what we should know before learning about static keywords in C++.

Prerequisites

The prerequisites to understanding the static keyword in C++ require you to know basic C++, such as functions and variables, as well as classes in C++. Memory allocation in C++ may also come in handy. Let us now take a look at the syntax for using C++ static.

Syntax

The syntax for the static keyword in C++ is very simple and easy. Just attach static before the variable or function or class object declaration, and it will be treated as static by C++.

We will look at the individual syntax later in this article when we approach the corresponding section for each, but in general, the syntax will be

Now that we have understood how to use the static keyword in C++ let us look at where we can use it and why it is so helpful.

Uses of Static Keywords in C++

The static keyword in C++ can be used in several ways, with different components in C++ as listed below :

  1. Variables:
    C++ Static variables maintain their value until the end of the program.
  2. Class objects:
    C++ Static class objects can be used repeatedly even when their scope ends.
  3. Class variables:
    Class variables declared as static can be used to define a constant class property as they are common to all class objects.
  4. Member functions:
    C++ Static member functions can be called without using an object in a class.

Example of Static Keyword in C++

Let us look at an example of the C++ static keyword.

Output:

In the above example, the variable temp has been declared static. It is clear from the output that this variable isn't reinitialized repeatedly, even when the function ends. Instead, it is initialized just once before the function is called, and it remains until the complete program ends, so by the end of the code, the final value of temp is 4. If the variable had not been declared static, it would be re-initialized each time the function is called, and hence we would get only 1 printed four times as the output.

In the next section, Let us explore how this single-time initialization of static variables takes place in C++.

Storage of Static Variables

A static variable is allocated memory only once during the complete program during its initialization.

But where is this memory allocated? All static variables are stored in a part of the virtual memory, called the data segment, unlike other variables that are allocated memory in the stack. Suppose the static variable is initialized with a value. In that case, it is stored in the initialized data segment, and in case it is uninitialized, it is given a default value of 0. It is stored in the uninitialized data segment, also called BSS (Block Started by Symbol). This allocated memory remains until the program ends, even if the function where the static variable was declared terminates.

Also, another thing to note is that static variables can only be initialized with constant values.

What are Static Variables in C++?

We have already examined how to use the C++ static keyword with variables. But even then, two subcategories exist when using the static keyword with variables. These are :

  1. Variables that are part of a function
  2. Variables that are class members

Let us look at both of these categories and the advantages of using the static keyword in them in detail.

C++ Static Variables in a Function

When declared in a function, static variables are not deallocated even if the function terminates. They stay in the memory until the program finishes executing. Why is this helpful?

We can store the state of a variable declared in the function and use it again in a program. In such a case, a static variable is very useful. Let us look at an example to understand more clearly.

Output:

As you can see in the above example, the variable ans has been declared static, so it is allocated memory space only once. That is why it isn’t reinitialized repeatedly, even when the function ends. Instead, it is initialized just once before the function is called, and it remains until the complete program ends. Hence, it stores its previous value even if the function has ended, making it easier to continue with the same value the next time.

C++ Static Variables in a Class

When variables that are members of a class are declared static, they are again allocated space only once throughout the program and deallocated only once the program ends. But as these variables are the member function of the class but declared as static, their copies cannot be made. This means that these variables have to be shared among the objects of the class.

This is why static variables of a class can't be initialized using a constructor. Instead, they have to be initialized outside the class explicitly using the scope resolution operator like class_name::variable_name = value. Note that the static variables will be shared and the same for all the objects of the class and hence can be used to store some common property for all the objects of the class while reducing redundancy.

Let us look at an example to understand static variables in a class in C++ better.

Output:

In the above example, the variable no_of_tyres denotes the number of tires the car has, which is the same for all cars. Hence, this variable has been declared static. Now it is shared among all objects of the Car class. To initialize or change the value of this member, we need to explicitly use the scope resolution operator, which cannot be done using the constructor or by accessing it through any object of the class.

Hence, in this way, the variables which are members of a class and are declared as static can be used to store information common for all class objects in C++.

What are C++ Static Members of a Class?

At the start of this article, we discussed how we can use the static keyword with not only variables but also objects and functions of a class in C++. Hence, this section will explore two categories of using a static keyword with class members :

  1. Static class objects
  2. Static class functions

Class Objects as Static

Like static variables in C++, static class objects in C++ are no different. So, static class objects are allocated memory only once during the program and deallocated after the completion of the program. Hence, even if the scope of wherever the object was declared ends, it remains in memory as it has been declared static. Like static variables, you can repeatedly use these objects with their previous value.

Let us look at an example in C++ to understand this better.

Output:

In the above code, we have declared a custom constructor as well as a destructor for the class objects so that a statement is printed whenever it is called. You will notice from the output that first, the program starts. After that, we call the createThing() function, and we create a new static object of the Things class. Hence the constructor is called, and the corresponding statement is printed. Now when the createThing() function ends, the scope of the object created in this function also ends, but the destructor is not called yet as it should be. This is because the object is declared static and will be deallocated only when the complete program ends. So first, the main() function is completely executed, then the destructor is called, and its corresponding statement is printed.

C++ Static Functions in a Class

Just like we can have static variable members in a class, we can also have member functions declared static inside a class using the static keyword in C++.

Like static variables, these static member functions can be called without any object using the class name and the scope resolution operator as class_name::function_name(). But this is not the only way to call the function. We can call them using class objects using the . operator. A very important thing to note is that these static member functions can only call static member variables and other static member functions, but not the other variables or functions.

Let us look at an example in C++ to understand this better.

Output:

In the above code, we first declared a static member function using the static keyword before the function declaration and description. You can see that we can call the static function without an object using the scope resolution operator and also by using an object like other normal member functions.

Practical Usage of the C++ Static Keyword

All the above codes we saw were examples of how we can use the static keyword to accomplish various things in C++. But the Singleton Design Pattern is the most widely used practical application of the static keyword. Before we learn how exactly this design is an application for the static keyword in C++, we will learn about the Singleton Design Pattern.

Singleton Design Pattern

The Singleton Design Pattern ensures that a class has only one instance throughout the program that can be accessed globally. This means that the same instance should persist throughout the program, and no other new instances should be made. Hence, this pattern provides a way of maintaining a global state as a single class instance. This global state should be globally accessible and can be shared among the different components of the program, which can access and update easily.

But how can this be achieved in C++? Using the static keyword, we can declare the class instance as a static variable. Also, inside our class, we can make the constructor private. This ensures that the constructor cannot be called anywhere in the program but only from the class. A second need is to ensure we can access the single instance globally. For this, we can declare a static member function of the class as public which can then access the constructor. Also, as this function is static, it can be accessed from anywhere in the program without needing a class object using the scope resolution operator. To ensure that if an instance of the class has been made, it isn't made again. Instead, the same instance is returned. We can use if and else statements in this static function, and only if an instance hasn't been made will we create a new one, or else the old one will be returned.

Let us look at the code for the same in C++ to understand this better.

Output:

As discussed above, this code will ensure that no one can access the constructor globally and always only one instance of the class remains. This is how the static keyword can be used to implement the Singleton Design Pattern.

Learn More

Scaler Topics

Conclusion

  • Variables or objects declared as "static" in C++ are initialized only once and are not deallocated until the termination of the complete program.
  • To declare a variable or object as static, append the keyword static in its declaration.
  • All static variables are stored in a part of the virtual memory called the data segment (initialized or uninitialized segment).
  • When using the static keyword in C++ with variables, we have two choices :
    1. Variables that are part of a function
    2. Variables that are class members
  • When using the static keyword in C++ with classes, we have two choices :
    1. Static class objects
    2. Static class functions
  • The most widely used practical application of the static keyword is the Singleton Design Pattern.
  • The Singleton Design Pattern ensures that a class has only one instance throughout the program, which can be accessed globally and implemented using the static keyword in C++.