Storage class in C++ is a foundational topic that is often ignored or glossed over in introductory courses or books on C++. Even small details impact the quality of your code, its performance, and maintainability, and therefore, learning and mastering storage class, a small concept in C++, is quite important. You must have used the static keyword while programming in C++. It is actually one of the keywords or objects of this class. In this article, we will discuss the storage classes, what they are, why learning them is so important, and we will look deeper into each of them.
Table of Contents:
What are Storage Classes in C++?
Storage class in C++ refers to a set of keywords that are used to define the features and behaviour of a variable. Features could include their scope, their lifecycle, their default values, or the default arguments (initial values) they take. These keywords also have a set of instructions that dictate to the compiler how to allocate and manage memory for variables and functions. The three key features determined in the storage class are:
- Scope: This indicates where in the program the variable is accessible. It may be throughout the program or in a particular block of code. All such information is stored in the storage class for that variable or function.
- Lifetime: How long a variable will stay in memory and when it will be destroyed is stored in C++ using the storage class keyword. A variable or a function may have a full lifetime (until the program ends) or have a temporary presence in memory.
- Default Initial Value: A default value is assigned when the user does not give any specific value to the program. It may be used to avoid exceptions and keep the program running.
Storage classes help the compiler understand how a variable should behave during program execution. In simple terms, it tells the compiler where to keep the variable, for how long, and who can use it.
Why are storage classes used in C++?
Storage class in C++ serves several important reasons, because of which developers use it to build efficient and well-structured applications. The reasons are explained below.
- Memory Management: A program can customize how long variables remain in memory and, as an extension, control the efficiency of the program and resource usage.
- Access Control: Through an object of the storage class, developers can also determine where variables can be accessed within a program. This helps organize the code and prevents any naming conflicts. This restricts or extends the visibility of a variable in the program.
- Performance Optimization: Certain objects in this class can suggest optimal storage locations (like CPU registers) for faster variable access.
Types of Storage Classes in C++
Various types of keywords are reserved to tell which variable or function lies under which storage class in C++. They all fulfil different purposes and requirements of the developer, and there are six major keywords. Let us look at them one by one in the sections explained below.
1. auto Storage Class
The auto keyword is used to let the compiler automatically detect the datatype of a variable based on the assigned value. In the versions before C++ 11, it was used to declare a local variable. The auto storage class is the default class of all the variables that are declared in a code block, meaning if no other storage class is assigned to a variable, it is automatically considered an auto class.
Properties of this class
- Scope: Local. These variables are not visible outside their block of code.
- Lifetime: According to its scope. It is destroyed when the block of code it was declared ends.
- Default Value: Garbage value. If the user does not give any value, then it takes up a garbage value.
Code:
Output:
Explanation: In this program, we did not specify a datatype while declaring the variable. Instead, we used the auto keyword. The compiler automatically detected the datatype and gave the output without any errors. The typeid().name() function is used to find out the data type of the variables. Type id ‘i’ stands for integers, d for double, and c for character.
Note: Ensure that your compiler supports C++ 11 for the above code to work.
2. extern Storage Class
The extern keyword is used to declare a variable that is defined in another file or another location, to inform the compiler to check there to successfully execute the code before throwing an error. It helps share the variables between multiple files. This keyword is highly used in big programs where data sharing between multiple files is crucial.
You can make a global variable an external variable by adding the extern keyword in front of the variable declaration.
Properties of this class
- Scope: Global. These variables can be accessed anywhere in the program.
- Lifetime: Same as the program. It stays in memory until the program is executing. Once the program is finished, this variable is also destroyed along with the program information.
- Default Value: Zero.
Code:
Output:
Explanation: Here, we declare a global variable in an extern storage class object. Since the online compilers are not able to compile and read two files at once, this example is not using an ‘external variable’ inside the code. You can perform that using your local compilers and IDEs with two different code files. Remember to define that variable as global that you want to use in another file.
Note: This is a simulated example of extern. In real-world use, extern is typically used to reference variables defined in a separate file.
Get 100% Hike!
Master Most in Demand Skills Now!
3. static Storage Class
A static storage class is versatile and may be confusing for beginners, as it changes its meaning based on where it is used in the program. Fundamentally, a static keyword preserves the value of the variable. Based on where it is used, it preserves the value of the variable accordingly.
- Local static variables are defined inside a function, and they remember their values across multiple function calls. The local static variable, like local variables, cannot be accessed outside its function block.
- Global Static variables are defined outside of any function block inside a program, and are limited to the file. This means it cannot be used as an external variable in different files.
Properties of this class
- Scope: Based on the type of static variable. The static keyword has local scope, and global has the entire program as scope.
- Lifetime: Same as the program. It stays in memory until the program is executing. Once the program is finished, this variable is also destroyed along with the program information.
- Default Value: Zero.
Code:
Output:
Explanation: In this code, each time localStaticDemo() is called, the localStaticVar is incremented by 1, and each time it retains its value for the next function call because it was defined as a static storage class object. The globalStaticVar is visible throughout the file and retains the value in the program. It can be modified in any function.
4. register Storage Class
The register storage class keyword in C++ indicates to the compiler to store this variable in the register instead of the RAM (main memory) if there are free register memory locations available. CPU registers are faster to access than RAM; therefore, they are declared when faster access to the variable in the program is a requirement.
Note: Modern compilers have automatic variable storage optimization phases, so the register keyword is not used as a storage class anymore, but is still part of the C++ language.
Code:
Output:
Explanation: Here, the variable is accessed repeatedly in a loop, which is where speed improvements could matter. When the number of times the loop is supposed to run is high.
5. mutable Storage Class
The mutable keyword allows for the modification of a class or struct variable in cases where the object is declared as const. In general, defining a variable as const means that changes to its members are not permitted. Mutable makes an exception by indicating that a particular type of change to this const class variable is permitted.
When a function is declared const, you cannot make any changes to the main data of the object. In general, this means that when an object member is used in that const function, they are read-only. However, if one of the members is marked as mutable, then that particular member can be changed by the const function, typically for non-critical changes like a cache or counter.
Code:
Output:
Explanation: The name variable is private, and the access counter is declared as a mutable variable. Therefore, the name variable cannot be modified as it is not declared mutable. Each time printName() is called, it increments accessCount because of the mutable storage class, even though the object s1 is declared as const.
6. thread_local Storage Class
The thread_local keyword is used to declare a variable specifically for a particular thread. It is born with the thread and is destroyed after the death of thread. This specifier was introduced in C++11 and can be used with others as well, like extern or static. Each thread has its own copy of the thread variable. The thread_local storage class ensures that each thread in a multi-threaded program has its own separate copy of the variable.
Code:
Output:
Explanation: The thread_local keyword ensures each thread has its own separate copy of a variable. In the code, three threads increment their counter, and each prints 1 because they are working with independent copies. This prevents data conflicts and is useful for thread-safe operations.
Conclusion
To conclude, we learned about the different types of storage classes that can be used in C++ to enhance and optimize the performance of your program. We learned about their scope, visibility, and default values in addition to understanding the features of each keyword. Though there are six major ones, one of them, the register storage class, is no longer in use. By the end of the article, you should now understand why learning storage classes, a concept so many books miss, is so important to know about to make your program optimized and powerful.
Storage Classes in C++ – FAQs
Q1. What are the storage classes in C++?
You can use them in C++ to define the scope, lifetime, and visibility of variables. Common types include auto, register, static, extern, and mutable.
Q2. How many storage class specifiers are offered by C++?
C++ offers five specifiers: auto, register, static, extern, and mutable (only for class members).
Q3. How many types of memory are there in C++?
C++ uses four memory types: stack, heap, static/global, and code/text segment for function instructions.
Q4. How many storage classes are there?
There are six main keywords in C++: auto, thread_local, static, extern, mutable (C++ only), and register, which is no longer in use.
Q5. Which storage class has global visibility in C++?
You can use the extern storage class to declare variables with global visibility across multiple files.