In C++, the keyword "static" functions as a modifier that is associated with the type rather than an instance. Therefore, it is not necessary to have an instance in order to access the static members. In the realm of C++, static elements can encompass fields, methods, constructors, classes, properties, operators, and events.
C++ utilizes the static keyword in multiple ways, such as prolonging the lifespan of variables, limiting their scope, and enhancing memory efficiency. This keyword plays a crucial role in controlling the access to variables, functions, and class members, while also governing their behavior.
Syntax
It has the following syntax:
static data_type variable_name; // For static variables
static return_type function_name(); // For static functions
class ClassName {
static data_type variable_name; // Static member variable
static return_type function_name(); // Static member function
};
C++ Static Field
A variable defined as static is known as a static field. In contrast to an instance field, which allocates memory each time an object is created, a static field has only a single instance stored in memory. This instance is shared among all objects.
It is employed to denote the shared attribute among all entities like rateOfInterest for an Account, companyName for an Employee, and so on.
C++ Static Field Example
Let's consider a basic illustration of an unchanging field in C++.
Example
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name; //data member(also instance variable)
static float rateOfInterest;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
}
void display()
{
cout<<accno<< " "<<name<< " "<<rateOfInterest << endl;
}
};
float Account::rateOfInterest=7.25;
int main(void) {
Account a1 =Account(101, "John"); //creating an object of Employee
Account a2=Account(102, "Alice"); //creating an object of Employee
a1.display();
a2.display();
return 0;
}
Output:
101 John 7.25
102 Alice 7.25
C++ Counting Objects Examples Using Static Keyword
Let's consider another instance of the static keyword in C++ that tracks the number of objects.
Example
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
int Account::count=0;
int main(void) {
Account a1 =Account(101, "John"); //creating an object of Account
Account a2=Account(102, "Alice");
Account a3=Account(103, "Michael");
Account a4=Account(104, "Harry");
a1.display();
a2.display();
a3.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}
Output:
101 John
102 Alice
103 Michael
103 Michael
Total Objects are: 4
Here, we will explore various static functions that are available for use in C++.
1. Static Variables in Functions
In C++, a static variable retains consistent values across multiple function executions, preventing repetitive initializations. Function-specific static variables are set once upon initialization and retain their values across subsequent function invocations.
C++ Static Variables in Functions Example
Let's consider an illustration to showcase the static variable concept in functions within the C++ programming language.
Example
#include <iostream>
void counter() {
static int count = 0; // Retains value across function calls
count++; //count function
std::cout << "Count: " << count << std::endl; //prints the count value
}
int main() //main function
{
counter();
counter();
counter();
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Explanation:
In this instance, a static variable named count is defined, ensuring that its value persists across function calls. The count variable retains its value and is not reset each time the function is invoked.
2. Static Data Members in Classes
In C++, the static data members are class elements established with the static keyword. They are common to all instances of the class and are associated with the class itself rather than individual instances. Multiple instances of the identical static variable do not exist for various objects.
C++ Static Data Members in Classes Example
Let's consider an illustration to showcase static data members within a class in the C++ programming language.
Example
#include <iostream>
class Student {
public:
static int count; // Declaration of static member
Student() { count++; }
};
int Student::count = 0; // Definition of static member
int main() {
Student s1, s2, s3;
std::cout << "Total Students: " << Student::count << std::endl;
return 0;
}
Output:
Total Students: 3
3. Static Member Functions in a Class
In C++, static member methods function autonomously from instances of any class, and they are restricted to accessing static class components.
C++ Static Member Function in a Class Example
Let's consider an illustration to demonstrate a static member function within a C++ class.
Example
#include <iostream>
class Counter {
private:
static int count;
public:
static void increment() {
count++;
std::cout << "Count: " << count << std::endl;
}
};
int Counter::count = 0;
int main() {
Counter::increment();
Counter::increment();
return 0;
}
Output:
Count: 1
Count: 2
Explanation:
The function modifies the increment static variable count, preserving its value across multiple function invocations, and can be invoked without instantiating an object.
4. Global Static Variables
A static global variable maintains an internal linkage that limits its scope to the specific file where it is defined. The internal linkage of static variables helps prevent conflicts that can arise across various files.
C++ Global Static Variables Example
Let's consider an example to illustrate the usage of global static variables in C++.
Example
#include<iostream>
static int globalCounter = 0; // Global static variable
void incrementCounter() {
globalCounter++;
std::cout << "Global Counter: " << globalCounter << std::endl;
}
int main() {
incrementCounter();
incrementCounter();
return 0;
}
Output:
Global Counter: 1
Global Counter: 2
Explanation:
The globalcounter variable maintains its value when called within functions, yet its scope is confined to the current source file due to the static keyword.
5. Static Variables in Namespaces
A static variable in a namespace functions in a comparable manner to a static global variable but confines its scope of usability to the current file.
C++ Static Variables in Namespace Example
Let's consider an illustration to showcase the static variables within namespaces in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
namespace Namespacefunc {
static int count = 0;
void increment() {
count++;
cout << "Count Number: " << count << endl;
}
}
int main() {
Namespacefunc::increment(); // Count: 1
Namespacefunc::increment(); // Count: 2
return 0;
}
Output:
Count Number: 1
Count Number: 2
6. Static Local Variables in Loops
In C++, a static variable within a loop maintains its value throughout successive iterations.
C++ Static Local Variables in Loops Example
Let's consider an illustration to showcase the static local variable in loops in C++.
Example
#include<iostream>
void loopCounter() {
static int count=0;
for(int i=0;i<3;i++)
{
count++;
std::cout<<" Loop Iteration: "<<count<<std::endl;
}
}
int main() {
loopCounter();
loopCounter();
return 0;
}
Output:
Loop Iteration: 1
Loop Iteration: 2
Loop Iteration: 3
Loop Iteration: 4
Loop Iteration: 5
Loop Iteration: 6
7. Static in Multithreading
In C++, concurrent threads sharing values of static variables can lead to data races in multithreaded programs.
C++ Static in Multithreading Example
Let's examine an illustration to showcase the concept of static in multithreading within C++.
Example
#include<iostream>
#include<thread>
void incrementCounter() {
static int counter = 0; // Shared among threads
counter++;
std::cout << "Counter: " << counter << std::endl;
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
return 0;
}
Output:
Counter: Counter: 2
2
Conclusion
In summary, the static keyword in the C++ programming language allows developers to implement efficient memory handling while upholding encapsulation principles and facilitating collaboration with shared data.
Static enables developers to leverage fundamental features such as preserving state within functions, sharing data at the class level, and imposing limitations on variable scope. In multi-threaded environments, it becomes crucial to handle data carefully to avoid race conditions.
C++ Static MCQs
- What is the key characteristic of a static local variable inside a function?
- Each time a function executes it resets the value of this variable.
- The local variable maintains its initial values throughout consecutive function executions.
- The variable maintains its initial state after initialization because modification is not possible.
- The variable receives an initial value of zero at all times.
- Which statement about static data members in a class is true?
- Objects of the class obtain their static data member copies
- A static data member requires an object from the class to access it.
- All instances of a class access a single static data member at once.
- The initial value for static data members must remain within the class definition.
- What can be the default value for a static variable, which is of type int and if it is not explicitly intilaized?
- Undefined
- Zero
- Garbage value
- Compiler error
- A static member function accesses all class instances through shared data.
- We can only access static members from the class inside a static member function.
- A static member function requires invocation with an instance of the class.
- A static data member exists outside the class definitions
- A static function offers the ability to access static and non-static class members.
- What is the objective of declaring global variable as static variable in C++ programming
- To make it accessible from other files
- The declaration of static preserves constant values
- Static declaration limits variable use to the file where it was first defined.
- Different functions can access multiple instances of the variable with static declaration.
Static declaration restricts the usage of a variable to the specific file where it was initially defined.