In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event.
C++ uses the static keyword for various functions that include extending variable lifetime duration and reducing scope accessibility while optimizing memory management. The static keyword enables access control for variables and functions as well as class members while managing their behavioural parameters.
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 field that is declared as static is called a static field. Unlike the instance field, which gets memory each time whenever we create an object, there is only one copy of the static field produced in the memory. It is shared with all the objects.
It is used to refer to the common property of all objects such as rateOfInterest in case of Account, companyName, Employee, etc.
C++ Static Field Example
Let us take a simple example of a static 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 us take another example of static keyword in C++ that counts the 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 discuss several static function that can be utilized in C++.
1. Static Variables in Functions
In C++, static variable contains determined values throughout separate function executions while avoiding continuous initializations. Static variables in function are initialized only once, and then these variables hold values even through function calls.
C++ Static Variables in Functions Example
Let's look at an example to demonstrate the static variable in functions in C++.
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 example, a variable count is declared as static. Therefore, the value is carried via the function calls. The variable count is not getting initialized every time the function is called.
2. Static Data Members in Classes
In C++, the static data members are class members that are defined using the static keyword. It is shared among all objects of the class and belongs to the class, not separate objects. There may not be multiple copies of the same static variable for several objects.
C++ Static Data Members in Classes Example
Let's look at an example to demonstrate static data members in the class in C++.
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 functions operate independently from objects of any class, and they can only access static class elements.
C++ Static Member Function in a Class Example
Let's look at an example to illustrate static member function in the class in C++.
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 updates the increment static variable count, which retains its value in several function calls, and is called without creating an object.
4. Global Static Variables
A static global variable retains an internal connection that confines its usage to the particular file where statements declare it. The internal linkage of static variables protects them from conflicts that occur between different files.
C++ Global Static Variables Example
Let's take an example to demonstrate the 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:
Globalcounter retains its value in variable function call, but due to static keywords remain limited to this source file.
5. Static Variables in Namespaces
A static variable within a namespace works similarly to a static global variable while maintaining its usage scope to the current file.
C++ Static Variables in Namespace Example
Let's take an example to demonstrate the static variables in 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 inside a loop retains its value across iterations.
C++ Static Local Variables in Loops Example
Let's look at an example to demonstrate the static local variabel 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++, static variables in multithreaded programs trigger data races because threads share their values.
C++ Static in Multithreading Example
Let's look at an example to demonstrate the static in multithreading in 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 conclusion, the static keyword functions within C++ programming language enable users to execute effective memory management while maintaining encapsulation rules alongside shared data cooperation.
Static allows programmers to benefit from essential functionality, which includes state retention within functions class-level data sharing and variable scope constraints. Threaded environments require special management of data to prevent racing 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.