C++

C++ Storage

C++ Storage

This section talks about C++ storage classes used to house variables or functions. In C++, a storage class defines the scope (visibility) and life-time of variables and/or functions used in a program. These specifiers precede the declaration type. There are following storage classes that can be used in a C++ Program.

auto 🡪 this is the default storage for all local variables.  For e.g.
{
     int x;
     auto int counter;

1. auto 🡪 this is the default storage for all local variables.  For e.g.

{
     int x;
     auto int counter;
	}

2. register 🡪 it defines local variables that you want to be stored in a CPU register instead of RAM. We need this for a variable that changes often and needs to be accessed very frequently. But this is an advisory to compiler. If no CPU register is free, then register directive is ignored and the variable is treated as normal local variable. The variable that needs to be stored in a register can be of size at most equal to the register size. Further, we can't have the unary '&' operator applied to it because it has no memory location. For e.g.

{
   register int  sum;
}

3.static 🡪static class tells the compiler to maintain the local variable during the entire life the program instead of creating and destroying it each time it comes into picture and goes out of frame. Therefore, static allows variable to maintain its values between function calls. The static modifier used in front of global variable causes its scope to be restricted to the file in which it is declared. So it becomes file scoped. For C++, a static data member of a class will make all objects of that class share the static data member. Similarly, static member functions of a class are allowed to access only the static data members or other static member functions, they cannot access the non-static data members or member functions of the class.

4.extern 🡪this class is used to give a reference of a global variable in order to make it visible to all the program files that forms part of the project. The keyword 'extern' in front of variable declaration tells the compiler that this variable name is defined at a storage location previously. For multiple file case, you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Point to remember is that extern is used to declare a global variable or function in another file.

5. mutable 🡪it applies only and only  to class objects. The mutable modifier a member of an object to override const member function i.e. a mutable member can be modified by a const member function.