Storage Classes in C++

In this section of the C++ tutorial, we will have a look at the storage classes in C++. Storage class in C++ is utilized to define the lifetime and visibility of a variable and/or function in a program.

Types of Storage Class in C++

There are five types of storage classes in the C++ programming language.

Storage Class Keyword Lifetime Visibility Initial Value
Automatic auto Function Block Within block Garbage
Register register Function Block Within block Garbage
Mutable mutable Class Within block Garbage
External extern Whole Program Global Zero
Static static Whole Program Within block Zero

Automatic Storage Class

For all the local variables, the auto storage class is the default storage class.

Following example shows how variables of auto storage class are declared:

int var; // by default, storage class is auto
auto int var;

Register Storage Class

For all the local variables that require to be stored in the RAM instead of the register, the register storage class is used.

Following example shows how variables of register storage class are declared:

register int var;

Mutable Storage Class

Mutable storage class is used only a class data member to make it modifiable even if the member is part of an entity considered to be const. The mutable specifier can not be used for a variable declared as static or const members or reference members.

Following example shows how variables of mutable storage class are declared:

class A
{
   public:
   mutable int x;
   int y;
};

External Storage Class

The external storage class is used to provide a global variable link that is accessible to ALL the files of the system. The variable can not be initialized when using ‘ external ‘ as all it does is point the name of the variable to a storage location previously defined.

Following example shows how variables of external storage class are declared:

extern int count; // declaration of variable ‘count’
int count; // definition of variable ‘count’

Static Storage Class

The scope of the static variable is local to the function in which it is defined, but when the execution of the function is over it does not die. In function calls, a static variable’s value persists.

Following example shows how variables of static storage class are declared:

static int count = 0;

Leave a Reply

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

Shopping cart