Lesson 143 +10 XP

Static Members

Static Members

Most member variables get their own copy in every object. A static member is different: there is exactly one copy that belongs to the class and is shared by every object. With five objects, or none, they all see the same storage.

Static member variables

class Car {
public:
  static int count;   // declaration: one shared copy
};
int Car::count = 0;   // definition outside the class

The definition outside the class matters: the static member needs real storage, and that live definition provides it. Helping with the classic "how many cars exist" counter across all objects.

Car a, b;
a.count = 5;
cout << b.count;   // 5  -  same shared storage

Static member functions

Static member functions can be called without any object, using the class name:

class Car {
public:
  static int counter;
  static void show() { cout << counter; }
};
int Car::counter = 3;
Car::show();   // prints 3

Why no this in static functions

A static function isn't invoked on a specific object, so it has no this pointer and can only access static members - never a non-static member of a particular object.

TL;DR

  • A static member variable is one copy shared by the class and all objects.
  • Declare it in the class and define it outside: int Car::count = 0;.
  • Static functions are called with Class::func(), no object needed.
  • No this in static functions, so non-static members are out of reach.