🧲 C++ Static Members – One Value for All Objects
In C++, static members belong to the class itself, not to any specific object. This means all objects share the same copy of the static member. Think of it like a shared notebook in a classroom! 📒
🔹 Static Variables Inside a Class
If you mark a variable static, all objects of that class will use the same value.
🔧 Example: Static Variable
#include <iostream>
using namespace std;
class Counter {
public:
static int count;
Counter() {
count++;
cout << "Object created. Total: " << count << endl;
}
};
int Counter::count = 0;
int main() {
Counter a;
Counter b;
Counter c;
return 0;
}
🧠 How It Works
static int count;→ Declaration inside the classint Counter::count = 0;→ Definition outside the class- All objects share the same
countvariable
🔹 Static Functions
Static member functions can only access static members of the class.
🔧 Example: Static Function
#include <iostream>
using namespace std;
class Tool {
public:
static int totalTools;
static void showCount() {
cout << "Total tools: " << totalTools << endl;
}
};
int Tool::totalTools = 5;
int main() {
Tool::showCount(); // No object needed
return 0;
}
🧾 Quick Summary
- Static variable: Shared by all objects
- Static function: Can be called without an object
- Use
ClassName::memberto access them
With static members, your class becomes smarter and more memory-efficient — like giving your objects a shared brain cell! 🧠