What is Static Member in C++: Explanation and Example
static member is a class variable or function shared by all objects of that class rather than each object having its own copy. It belongs to the class itself, so it can be accessed without creating an object.How It Works
A static member in C++ is like a shared resource for all objects of a class. Imagine a classroom where every student has their own notebook, but there is also one whiteboard everyone can see and write on. The whiteboard is like a static member: it belongs to the whole class, not to any single student.
When you declare a member as static, it means there is only one copy of that member, no matter how many objects you create. All objects share and can change this single copy. This is different from normal members, where each object has its own separate copy.
Static members are stored in a special area of memory, separate from the individual objects. You can access static members using the class name directly, without needing to create an object first.
Example
This example shows a class with a static member variable that counts how many objects have been created.
#include <iostream> using namespace std; class Counter { public: static int count; // static member variable Counter() { count++; // increase count when object is created } static void showCount() { // static member function cout << "Number of objects: " << count << endl; } }; // Initialize static member outside the class int Counter::count = 0; int main() { Counter c1; Counter c2; Counter::showCount(); // Access static function without object Counter c3; c3.showCount(); // Access static function with object return 0; }
When to Use
Use static members when you want to share data or behavior across all objects of a class. For example, counting how many objects exist, managing shared settings, or implementing a single shared resource.
Static members are useful in cases like:
- Tracking the number of instances created from a class.
- Storing configuration values common to all objects.
- Providing utility functions related to the class but not tied to any object.
This helps save memory and keeps shared information consistent.
Key Points
- Static members belong to the class, not individual objects.
- Only one copy of a static member exists, shared by all objects.
- Static members can be accessed using the class name without creating objects.
- Static member variables must be defined outside the class.
- Static member functions can only access static members directly.