Skip to content

Static vs Instance Members

Instance Members: Belong to each object separately. Every object has its own copy.

Static Members: Belong to the class itself, not any object. Shared across all objects.

Think: Instance member = Each employee has their own salary. Static member = Company name is same for all employees.

Example

cpp
class Employee {
public:
    string name;      // instance — each object has own copy
    int salary;        // instance — each object has own copy
    static int count;  // static — shared among ALL objects

    Employee(string n, int s) {
        name = n; salary = s;
        count++; // increments shared counter
    }

    static void showCount() {
        cout << "Total Employees: " << count << endl;
    }
};

// static member must be defined outside class
int Employee::count = 0;

int main() {
    Employee e1("Alice", 50000);
    Employee e2("Bob", 60000);
    Employee e3("Charlie", 70000);
    Employee::showCount(); // Total Employees: 3
}

Key Differences

Instance MembersStatic Members
Belongs toEach objectClass itself
MemorySeparate per objectSingle shared copy
AccessVia object e1.nameVia class Employee::count
KeywordNonestatic
this pointerAvailableNot available
Defined outsideNoYes (must)

Static Method Restrictions

cpp
class Demo {
public:
    int x;         // instance variable
    static int y;  // static variable

    static void show() {
        cout << y << endl; // OK — can access static
        cout << x << endl; // ERROR! no 'this' pointer
    }
};

Static methods cannot access instance members because they have no this pointer.

Memory Layout

Object e1              Object e2              Object e3
├── name = "Alice"     ├── name = "Bob"       ├── name = "Charlie"
└── salary = 50000     └── salary = 60000     └── salary = 70000
              \                |                    /
               \_______________|___________________/
                    shared static: count = 3

Access — Always Prefer Class Name

cpp
Employee::count;       // recommended — via class name
Employee::showCount();

e1.count;               // also works but not recommended

Common Use Cases of Static

  • Counter — tracking number of objects: static int count;
  • Singleton pattern — only one instance allowed: static Demo* instance;
  • Shared config/constants: static const string VERSION = "1.0.0";

One-liner: "Instance members are unique to each object, while static members belong to the class and are shared across all objects, existing even without any object creation."