Explain static Data and Static member functions with example
In : BCA Subject : OOPS and Data StructuresA static data member is shared among all objects of a class. A static function can only access static variables or call other static functions .
Example :
#include
using namespace std;
class Counter {
private:
static int count;
public:
Counter() {
count++;
}
~Counter() {
count--;
}
// Static function to get count
static int getCount() {
return count; // Can only access static members
}
};
int Counter::count = 0; // Definition of static member
int main() {
cout << "Initial count: " << Counter::getCount() << endl;
Counter c1, c2, c3;
cout << "After creating 3 counters: " << Counter::getCount() << endl;
{
Counter c4;
cout << "Inside new scope: " << Counter::getCount() << endl;
} // c4 destroyed
cout << "Final count: " << Counter::getCount() << endl;
return 0;
}