In C++, static variables are a specific type of variable that persists throughout the entire duration of the program's execution. However, the scope of these variables can be limited depending on where they are declared. We previously discussed how the static keyword alters a variable's behavior, guaranteeing that its value endures even after the block or function where it was initially declared has finished running.
Static variables prove to be highly advantageous in scenarios where there is a requirement to retain a shared attribute or monitor collective information among numerous objects. They play a crucial role in reducing repetition and ensuring uniformity throughout all iterations.
C Static Variable Example
Let's consider an example to demonstrate the usage of a Static variable in the C programming language.
Example
#include <iostream>
using namespace std;
class cpptutorialTech
{
public:
string account_holder;
int account_balance;
static int total_accounts;
cpptutorialTech(string name, int balance)
{
account_holder = name;
account_balance = balance;
total_accounts++;
}
void display()
{
cout << "Account Holder Name: " << account_holder << ", Balance: $" << account_balance << endl;
}
};
int cpptutorialTech::total_accounts = 0;
int main() //main function
{
cpptutorialTech acc1("Joseph", 50000);
cpptutorialTech acc2("John", 40000);
cpptutorialTech acc3("Mary", 20000);
acc1.display();
acc2.display();
acc3.display();
cout << "Total Bank Accounts Created: " << cpptutorialTech::total_accounts << endl;
return 0;
}
Output:
Account Holder Name: Joseph, Balance: $50000
Account Holder Name: John, Balance: $40000
Account Holder Name: Mary, Balance: $20000
Total Bank Accounts Created: 3
Explanation:
In this illustration, we introduce a cpptutorialTech class that symbolizes a bank account along with a static variable totalaccounts, responsible for monitoring the total count of created accounts. Upon the creation of a cpptutorialTech object, the constructor defines the account details and increments totalaccounts, a value accessible by all objects. Following the establishment of three accounts and the display of their particulars, the script utilizes the static variable to compute the total count of all created accounts.
Types of Static Variables in C++
There are several static variables that can also be categorized into three essential categories:
- Static Variables Inside Functions
- Static Member Variables in Classes
- Global Static Variables
Static Variables Inside Functions
In C++, if a variable is defined as static within a function, it maintains its value between different invocations of the function. Ordinarily, local variables are instantiated at the start of a function's execution and deallocated when it finishes. Nevertheless, a static local variable is initialized solely during the initial invocation of the function and persists until the program terminates. Subsequent calls to the function access the most recent updated value of the static variable.
C++ Static Variable Inside Functions Example
Let's consider an example to demonstrate the concept of Static variables within functions in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
void display()
{
static int c = 0;
// Initialized only once.
c++;
cout << "Count is: " << c << endl;
}
int main() //main function
{
display();
display();
display();
return 0;
}
Output:
Count is: 1
Count is: 2
Count is: 3
Explanation:
In this code snippet, there is a display function that includes a static variable c. This variable is initialized only once and retains its value across multiple function calls. Upon each invocation of the display function, c is increased by one and then displayed. Consequently, executing the display function thrice will yield the consecutive outputs of 1, 2, and 3.
Static Member Variables in Classes
When a variable is declared as static within a class, it is associated with the class itself instead of any particular object. This indicates that all instances of the class share the same static variable. Static elements are initialized externally to the class and persist regardless of any of its instances.
C++ Static Member Variables in Classes Example
Let's consider an example to demonstrate the concept of Static member variables in C++ classes.
Example
#include <iostream>
using namespace std; //using standard namespace
class cpptutorialTech
{
public:
static int object_count;
cpptutorialTech()
{
object_count++;
}
};
int cpptutorialTech::object_count = 0;
// Initialization outside of the class.
int main() //main function
{
cpptutorialTech a, b, c;
cout << "Total objects created are: " << cpptutorialTech::object_count << endl;
return 0;
}
Output:
Total objects created are: 3
Explanation:
In this instance, we are examining the cpptutorialTech class which contains a static member function named objectcount. This function is responsible for monitoring the total number of class objects that have been instantiated. Subsequently, the objectcount function is incremented each time the constructor is invoked. Within the main function, three objects (a, b, and c) are instantiated.
Global Static Variables
When a global variable is defined in a C++ program using the static keyword, its visibility is restricted to the source file where it is declared. This restriction ensures that the variable remains inaccessible from other files. This approach aids in encapsulation, concealing implementation specifics, and averting naming clashes in extensive programs consisting of multiple source files.
C++ Global Static Variables Example
Let's consider an example to illustrate the Global static variable in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
static int db_connection_count = 0; // using Global static variable to track the number of active database connections
void ConnectToDatabase()
{
db_connection_count++;
cout << "Connecting to database... \nConnection count: " << db_connection_count << endl;
}
void CloseDatabaseConnection()
{
if (db_connection_count > 0)
{
db_connection_count--;
cout << "Database connection closed. \nRemaining connections: " << db_connection_count << endl;
}
else
{
cout << "No active database connections to close.\n";
}
}
int main() //main function
{
ConnectToDatabase();
ConnectToDatabase();
CloseDatabaseConnection();
return 0;
}
Output:
Connecting to database...
Connection count: 1
Connecting to database...
Connection count: 2
Database connection closed.
Remaining connections: 1
Explanation:
In this demonstration, we create a basic database connection monitor by employing a global static variable named dbconnectioncount. Subsequently, each invocation of the ConnectToDatabase function results in an increment of the count, while the CloseDatabaseConnection function leads to a decrement, effectively managing the closure of only active connections. Ultimately, the displayed result showcases the sequential connection and disconnection operations.
Storage of Static Variables in C++
In C++, the static variable is employed to reserve memory only once throughout the program's execution and maintains its value across different function calls. In contrast to local variables that reside on the stack, static variables are primarily stored in a specialized memory region referred to as the data segment.
If a static variable is explicitly initialized within the program, its value is stored in the initialized data segment. In cases where it is not explicitly initialized, it defaults to 0 and is placed in the BSS (Block Started by Symbol) segment. This segment is designated for uninitialized global or static variables. Static variables retain their memory allocation throughout the program's execution, independent of the function or scope where they were declared.
Applications of Static Variables in C++
Several applications of static variables in C++ are as follows:
- Preserving state between function calls: Static variables store their values between calls to the same function. It allows a function to "remember" what happened in earlier calls and apply that information to the present execution.
- Restricting scope to a function or file: A static variable specified within a function or file is linked internally. It means that it cannot be accessed from outside the function or file, which helps with logic encapsulation and preventing name conflicts.
- Efficient memory usage in classes: Static data members of a class are shared by all instances. When the same data is used across multiple objects, only one copy is made, which optimizes memory use.
- Counting Instances of a Class: Static variables are commonly used to display how many objects of a class have been produced because all instances share them and can be updated without the requirement for an object.
- Implementing Singleton Pattern: Static variables are important in the Singleton design pattern because they store a single instance of a class that is reused during the program.
C++ Static Variables MCQs
1) What is the lifetime of a static variable defined within a function in C++?
- Until the function terminates.
- Until an object is destroyed.
- Until the program ends.
- It depends on the scope.
2) Which of the following options correctly declares a static variable inside a class in C++?
- int static count;
- static int count = 0;
- int count static;
- count static int;
3) Which of the following options shows the scope of a global static variable in C++?
- Class only
- Entire program
- The file in which it is declared
- Main function only.
4) When a static variable is initialized inside a function in C++?
- After the program ends
- Only once, on the first function call
- At compile time
- Every time the function is called
5) What happens if a static variable is accessed without first being initialized in C++?
- It automatically gets garbage value
- It causes a runtime error
- It throws a compile error
- It is initialized to zero by default