What are Storage Classes in C++ Language with Examples

Storage Classes in C++ are used to explain what a variable or function can do.

These features are mostly the scope, visibility, and lifetime, which tell us how long a variable exists while a program runs.

The following syntax is used to say which memory is allocated:

storage_class var_data_type var_name;

Introduction

These characteristics enable us to track the presence of a variable throughout a program’s execution.

This article will look at various storage classes and code examples that show how they work.

Prerequisites

To start working on the project with the help of this article, make sure you have a code editor like Codeblocks installed on your computer and further knowledge about C++ language.

If you have not, visit Codeblocks IDE Free Download.

What is lifetime and visibility?

The visibility of a variable means whether or not it can be used in a certain part of code or in the whole program.

A variable’s lifetime is the amount of time it takes up a valid space in the system’s memory.

There are three kinds of lifetimes: static, automatic, and dynamic.

Types of C++  Storage Classes

A storage class tells a C++ program where variables and/or functions can be seen and how long they can exist.

These things come before the type they change. In a C++ program, the following storage classes can be used.

  • auto
  • register
  • static
  • extern
  • mutable

Automatic C++ Storage Classes

The auto keyword allows you to use type inference, which lets you automatically figure out the data type of an expression in a programming language.

This saves time because the compiler doesn’t have to be told things it already knows.

As the compiler only determines all types, this makes the compilation time a little longer, but it doesn’t change how long the program takes to run.

In addition, the feature works with functions and template parameters that are not types. Since C++14, functions’ return types can be determined by looking at their return statements.

Since C++17, if a template parameter is not a type, the type will be figured out by looking at the argument.

Syntax:

auto datatype var_name1 [= value];

Example Program:
#include <iostream>
using namespace std;
 
void autoStorageClass()
{
 
    cout << "Demonstrating auto class\n";
 
    //  auto variable declaration
    // No data-type declaration needed
    auto a = 32;
    auto b = 3.2;
    auto c = "itsourcecode";
    auto d = 'i';
 
    // printing the auto variables
    cout << a << " \n";
    cout << b << " \n";
    cout << c << " \n";
    cout << d << " \n";
}
 
int main()
{
 
    // To demonstrate auto Storage Class
    autoStorageClass();
 
    return 0;
}

Output:
Demonstrating auto class
32 
3.2 
itsourcecode
i

In the above example, there are two variables with the same storage class.

The auto keyword can only be used within functions, so these variables are called “local variables.”

You can test the above example here! ➡ C Online Compiler

Register C++ Storage Classes

In most programs, the register storage class is used to declare a few variables that need to be accessed often.

This helps speed up how fast the program runs. Pointers can’t be used to find the address of a variable in a register.

The largest size of the variable is the same as the largest size of the register. We can’t use the “&” operator because it doesn’t have a place in memory.

Syntax:

 register datatype var_name1 [= value];

Example Program:
#include <iostream>
using namespace std;

void registerStorageClass()
{

	cout << "Demonstration of register storage class\n";

	// declaration of a register variable
	register char c = 'G';

	//Lets dispkay the register variable
	cout << "Value of 'c' which is"
		<< " declared as register: " << c;
}
int main()
{

	// Demonstrating the Storage Class
	registerStorageClass();
	return 0;
}

Output:
Demonstration of register storage class
Value of c which is declared as register: G

The register is for fast-access variables like counters. Defining ‘register’ does not save the variable in a register.

Depending on hardware and implementation, it MAY be saved in a register.

You can test the above example here! ➡ C Online Compiler

Static C++ Storage Classes

This storage class is used to declare static variables. Static variables always have the same value, even when not used.

They are set up once and stay in place until the program ends. The memory location is only given to the static variable once, and no more is given because it is not re-declared.

Anywhere in the code, we can use global static variables. By default, the compiler gives them the value 0 for each one.

When static is used on a class data member in C++, all objects in that class share the same copy of that member.

Syntax:

static datatype var_name1 [= value];

Example Program:
#include <iostream>
 
// Function calls
void func(void);
 
static int count = 10; /* Global variable */
 
main() {
   while(count--) {
      func();
   }
   
   return 0;
}

// Function definition
void func( void ) {
   static int i = 5; // local static variable
   i++;
   std::cout << "i is " << i ;
   std::cout << " and count is " << count << std::endl;
}

Output:
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

When the code above is put together and run, the following happens.

Basically, the local static variables are incremented, and the global variable decreases.

You can test the above example here! ➡ C Online Compiler

External C++ Storage Classes

With the external storage class, you can point to a global variable that ALL program files can see.

When you use “extern,” you can’t set up a variable because all it does is point the variable’s name to a place already set up.

When you have more than one file, and you define a global variable or function that will be used in more than one file, you will use an extern to refer to the defined variable or function in another file.

For your information, an extern is used to declare a global function or variable in another file.

Furthermore, the extern modifier is used when two or more files share the same global variables or functions, as shown below.

Syntax:

extern datatype var_name1;

Example Program:
void externStorageClass()
{

	cout << "Demonstrating extern class\n";

	// We tell compiler that variable m is an extern variable. 
	// It's been defined somewhere else (above the main function)
	extern int m;

	// printing variables
	cout << "Value of 'm'which is "
		<< "declared as extern: " << m << "\n";

	// value of 'm' modified
	m = 5;

	// printing the modified values of
	// extern variables
	cout
		<< "Modified value of 'm'"
		<< " declared as extern: \n"
		<< m;
}
int main()
{
	// Demonstration of extern Storage Class
	externStorageClass();
	return 0;
}

Output:
Demonstration of extern class
Value of ‘m’ which is declared as extern: 0
Modified value of ‘m’ declared as extern: 5

The output above shows how to get the variable from other files using the ‘extern’ specifier.

You can test the above example here! ➡ C Online Compiler

Mutable C++ Storage Classes

The mutable specifier only works on class objects, which will be talked about in the next section of this tutorial.

It lets a member of an object take over the function of a const member.

That is, a const a member function can change a member that can change.

Syntax:

mutable datatype var_name1 [= value];

Example Program:
#include <iostream>
using std::cout;
 
class Test {
public:
    int x;
 
    // defining mutable variable y
    // now this can be modified
    mutable int y;
 
    Test()
    {
        x = 4;
        y = 10;
    }
};
 
int main()
{
    // t1 is set to constant
    const Test t1;
 
    // trying to change the value
    t1.y = 20;
    cout << t1.y;
 
    // Uncommenting below lines
    // will throw error
    // t1.x = 8;
    // cout << t1.x;
    return 0;
}

Output:

20

The Mutable C++ Storage Classes code above simply demonstrates that if y a variable already has a value that will possibly change using a “mutable” specifier.

You can test the above example here! ➡ C Online Compiler

Summary

In this article, we talked about the different methods we can use in C++ programs as storage classes, as well as what they are and what they do.

With this information, you should be able to make programs that use storage classes to show how variables and methods behave.

I hope this article was easy to understand and helpful for your future projects.

Leave a Comment