
Static Data Members and Functions in C++
In daily life, some things are shared by everyone rather than belonging to just one person. For example, in a classroom the notice board is the same for all students. If one student puts a notice, every student can see it. Similarly, in a society, the water tank is shared by all houses. In C++, such shared values or functions are handled using the static keyword.
A static member in C++ belongs to the class itself rather than to individual objects, and its value is shared among all objects of that class.
Why Do We Need Static?
Contents
- Shared Data: Some values are common for all objects. For example, the total number of students in a class is the same information for all students.
- Memory Efficiency: Instead of each object having its own copy, only one shared copy is created.
- Persistence: A static variable keeps its value throughout the program execution, instead of being created and destroyed repeatedly.
Static Variables Inside Functions
Normally, when a variable is declared inside a function, it is created every time the function is called and destroyed when the function ends. But if it is declared as static, it is created only once and remembers its value between function calls.
#include <iostream>
using namespace std;
void demo() {
static int x = 0; // created only once
x++;
cout << "x = " << x << endl;
}
int main() {
demo();
demo();
demo();
return 0;
}
Output:
x = 1
x = 2
x = 3
Static Data Members in Classes
When a variable is declared as static inside a class, it is shared by all objects of that class. Only one copy exists in memory.
Program Example: Counter
#include <iostream>
using namespace std;
class counter {
public:
static int count; // Declaration of static variable
counter() {
count++; // Every new object increases the same shared count
}
static void show() { // static function
cout << "The value of counter is: " << count << endl;
}
};
// Definition of static variable outside the class
int counter::count = 0;
int main() {
counter C1;
C1.show();
counter C2;
C2.show();
counter C3;
counter::show(); // Can also be called using class name
cout << "Try programiz.pro" << endl;
return 0;
}
Explanation
static int count;→ declared inside the class.int counter::count = 0;→ defined outside the class.- Every time a new object (
C1,C2,C3) is created, the constructor incrementscount. - The function
show()is declared static, so it can be called without creating an object (e.g.,counter::show();). - All objects share the same
count.
Daily Life Example
Think of class attendance:
Each student can be thought of as an object, while the attendance register in the classroom is a single shared record. No matter how many students there are, they all refer to and update the same register when marked present. In the same way, the static variable count is like that register—every object (student) updates the same shared value.
Static Member Functions
A static function inside a class can be called without creating an object. It only works with static data members, since those are also shared.
class MyClass {
public:
static int value;
static void display() {
cout << value << endl;
}
};
Comparison: Normal vs Static Members
| Aspect | Normal Member | Static Member |
|---|---|---|
| Storage | Each object has a copy | Shared by all objects |
| Lifetime | Created/destroyed with obj | Exists till program ends |
| Access | Through objects only | Through objects or class |
| Memory Efficiency | Less efficient (duplicates) | More efficient (single copy) |
Practice Exercises
- Write a program to count how many objects of a class are created using a static variable.
- Create a static function in a class that displays the total number of books in a library.
- Demonstrate a static variable inside a function that keeps its value across multiple calls.
25 thoughts on “Static Data Members and Functions in C++”
**mind vault**
mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking
**prostadine**
prostadine is a next-generation prostate support formula designed to help maintain, restore, and enhance optimal male prostate performance.
**sugarmute**
sugarmute is a science-guided nutritional supplement created to help maintain balanced blood sugar while supporting steady energy and mental clarity.
**gl pro**
gl pro is a natural dietary supplement designed to promote balanced blood sugar levels and curb sugar cravings.
**vitta burn**
vitta burn is a liquid dietary supplement formulated to support healthy weight reduction by increasing metabolic rate, reducing hunger, and promoting fat loss.
**synaptigen**
synaptigen is a next-generation brain support supplement that blends natural nootropics, adaptogens
**zencortex**
zencortex contains only the natural ingredients that are effective in supporting incredible hearing naturally.
**yusleep**
yusleep is a gentle, nano-enhanced nightly blend designed to help you drift off quickly, stay asleep longer, and wake feeling clear.
**nitric boost**
nitric boost is a dietary formula crafted to enhance vitality and promote overall well-being.
**glucore**
glucore is a nutritional supplement that is given to patients daily to assist in maintaining healthy blood sugar and metabolic rates.
**wildgut**
wildgutis a precision-crafted nutritional blend designed to nurture your dog’s digestive tract.
**breathe**
breathe is a plant-powered tincture crafted to promote lung performance and enhance your breathing quality.
**energeia**
energeia is the first and only recipe that targets the root cause of stubborn belly fat and Deadly visceral fat.
**boostaro**
boostaro is a specially crafted dietary supplement for men who want to elevate their overall health and vitality.
**pineal xt**
pinealxt is a revolutionary supplement that promotes proper pineal gland function and energy levels to support healthy body function.
**prostabliss**
prostabliss is a carefully developed dietary formula aimed at nurturing prostate vitality and improving urinary comfort.
**potentstream**
potentstream is engineered to promote prostate well-being by counteracting the residue that can build up from hard-water minerals within the urinary tract.
**hepatoburn**
hepatoburn is a premium nutritional formula designed to enhance liver function, boost metabolism, and support natural fat breakdown.
**hepato burn**
hepato burn is a potent, plant-based formula created to promote optimal liver performance and naturally stimulate fat-burning mechanisms.
**cellufend**
cellufend is a natural supplement developed to support balanced blood sugar levels through a blend of botanical extracts and essential nutrients.
**prodentim**
prodentim is a forward-thinking oral wellness blend crafted to nurture and maintain a balanced mouth microbiome.
**flow force max**
flow force max delivers a forward-thinking, plant-focused way to support prostate health—while also helping maintain everyday energy, libido, and overall vitality.
**revitag**
revitag is a daily skin-support formula created to promote a healthy complexion and visibly diminish the appearance of skin tags.
**neurogenica**
neurogenica is a dietary supplement formulated to support nerve health and ease discomfort associated with neuropathy.
**memory lift**
memory lift is an innovative dietary formula designed to naturally nurture brain wellness and sharpen cognitive performance.