C++ Storage Classes
In C++, storage classes are used to specify the scope, life time, and visibility of variables, functions, and objects. There are four main storage classes in C++: auto, register, extern, static, and mutable.
Auto
The auto storage class is the default storage class in C++ and is used for automatic variables. These variables are declared within a function and are automatically destroyed at the end of the function.
Example:
1#include <iostream> 2using namespace std; 3 4void func() 5{ 6 auto int a = 10; 7 cout << "The value of a is: " << a; 8} 9 10int main() 11{ 12 func(); 13 return 0; 14}
Output:
The value of a is: 10
Register
The register storage class is used for variables that are stored in the CPU's register. This can improve the performance of a program by reducing the amount of memory access required.
Example:
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 register int a = 10; 7 cout << "The value of a is: " << a; 8 return 0; 9}
Output:
The value of a is: 10
Extern
The extern storage class is used to declare variables or functions that are defined in another source file. This is useful when you need to use a variable or function in multiple files.
Example:
1// file1.cpp 2#include <iostream> 3using namespace std; 4 5extern int a; 6 7void func() { 8 cout << "The value of a is: " << a; 9} 10 11// file2.cpp 12#include <iostream> 13using namespace std; 14 15int a = 10; 16 17int main() { 18 func(); 19 return 0; 20}
Output:
The value of a is: 10
Static
The static storage class is used for variables that have a single instance of the variable for the entire program. This means that the value of the variable persists between function calls and is not destroyed when a function ends.
Example:
1#include <iostream> 2using namespace std; 3 4void func() 5{ 6 static int a = 10; 7 a++; 8 cout << "The value of a is: " << a; 9} 10 11int main() 12{ 13 func(); 14 func(); 15 func(); 16 return 0; 17}
Output:
1The value of a is: 11 2The value of a is: 12 3The value of a is: 13
Mutable
The mutable storage class is used for class member variables. It allows the value of a member variable to be changed even if the member function that changes it is declared as a constant.
Example:
1#include <iostream> 2using namespace std; 3 4class A 5{ 6public: 7 mutable int x; 8 int y; 9 10 void func() const { 11 x = 10; 12 // y = 10; // error: cannot as 13 const member function 14 } 15}; 16 17int main() { 18 A a; 19 a.x = 5; 20 a.y = 5; 21 a.func(); 22 cout << "The value of x is: " << a.x << endl; 23 cout << "The value of y is: " << a.y << endl; 24 return 0; 25}
Output:
1The value of x is: 10 2The value of y is: 5