What is Static Keyword in C++?
Static means something which is shared and does not change for every object. Normal variable is different for every object, but static variable is same for all objects.
Think like this: In a school, every student has different name, but school name is same for all students. School name is like static.
Static Variable in Class:
include
using namespace std;
class Student {
public:
int rollNo;
static int count; // Static Variable
Student() {
count++;
}
};
int Student::count = 0; // Must define outside
int main() {
Student s1, s2, s3;
cout << "Total Students: " << Student::count << endl;
return 0;
}
Output:
Total Students: 3
Here count is shared by all objects. s1, s2, s3 all increase the same count. If it was normal variable, every object would have its own count = 1.
Static Function in Class:
Static Function can be called without creating object. It can only access static data.
Example:
include
using namespace std;
class Counter {
public:
static int count;
static void showCount() {
cout << "Count is: " << count << endl;
}
};
int Counter::count = 5;
int main() {
Counter::showCount(); // No object needed
return 0;
}
Output:
Count is: 5
Static Variable in Function:
When we make a variable static inside a function, its value is remembered even after function ends.
Example:
include
using namespace std;
void show() {
static int num = 0;
num++;
cout << num << endl;
}
int main() {
show();
show();
show();
return 0;
}
Output:
1
2
3
Normal variable would print 1, 1, 1 every time because it resets. Static variable remembers its old value.
Conclusion:
Static Variable = One copy for all, shared.
Static Function = Call without object.
Static in Function = Value remembers.
Static Keyword is very important for interviews and exams.
I have tested this code myself and it works perfectly.
Top comments (0)