Storage classes
are used to specify the visibility/scope and life time of symbols (functions
and variables). That means, storage classes specify where all a variable or
function can be accessed and till what time those variables will be available
during the execution of program.
Following storage classes are available in C++,
Following storage classes are available in C++,
- Auto:
Auto is the default storage class for local variables. They can
be accessed only from within the declaration scope. auto variables are allocated at the beginning of enclosing block and
deallocated at the end of enclosing block.
- Register:
Register storage class is similar to auto variables. Difference is that register
variables might be stored on the processor register instead of RAM, that means
the maximum size of register variable should be the size of CPU register ( like
16bit, 32bit or 64bit). This is normally used for frequently accessed variables
like counters, to improve performance. But note that, declaring a variable as
register does not mean that they will be stored in the register. It depends on
the hardware and implementation.
- Static:
A static variable
will be kept in existence till the end of the program unlike creating and
destroying each time they move into and out of the scope. This helps to
maintain their value even if control goes out of the scope. When static is used
with global variables, they will have internal linkage, which means it cannot
be accessed by other source files. When static is used in case of a class
member, it will be shared by all the objects of a class instead of creating
separate copies for each object.
- Extern:
extern is used to
tell compiler that the symbol is defined in another translation unit (or in a
way, source files) and not in the current one. Which means the symbol is linked
externally. Extern symbols have
static storage duration, which is accessible throughout the life of program.
Since no storage is allocated for extern variable as part of declaration, they
cannot be initialized while declaring.
- Mutable:
mutable storage
class can be used only on non static non const data a member of a class.
Mutable data member of a class can be modified even if it's part of an object
which is declared as const.