Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 171 ยท Object-Oriented Programming

Static Members

Learn C++ static members - class-wide data, inline static and constexpr static members, static member functions, instance counters, and why singletons cause trouble.

Every object of a class normally gets its own copy of each data member: two Player objects have two separate health values. Sometimes, though, a piece of data belongs to the class as a whole: how many objects exist right now, the next ID to hand out, a shared configuration limit, a lookup table every object reads. Declaring such a member static gives you exactly one copy, shared by all objects and existing even when there are no objects at all.

Member functions can be static too. A static member function belongs to the class rather than to an object, so it has no this pointer and can be called without any object. In this lesson you'll learn how to declare and define static data (including the modern inline static and static constexpr forms), how static functions differ from ordinary members, common patterns such as counters and named constructors, and why the famous singleton pattern is usually a mistake.

Static data members

A static data member is declared inside the class with static. It is stored once, outside every object, and has static storage duration: it is created before main runs (for most types) and destroyed after main returns, like a global variable. The difference from a global is that its name lives inside the class's scope and obeys access specifiers.

C++ One counter shared by all objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each constructor call reads the shared next_number_ and increments it, so the tickets get 1, 2 and 3. Notice that sizeof(Ticket) only counts the std::string and the int; the static member isn't stored in the object.

Defining static members: old and new

The keyword inline in inline static int next_number_ = 1; is a C++17 feature, and it matters. A plain static data member inside the class is only a declaration. Before C++17 you had to write the definition, exactly once, in one .cpp file:

C++
// ticket.h
class Ticket {
    static int next_number_;          // declaration only
};

// ticket.cpp
int Ticket::next_number_ = 1;         // the one definition (no 'static' here)

Forget the definition and the code compiles but fails to link with "undefined reference to Ticket::next_number_". Put it in the header and every .cpp file that includes the header defines it again, which is also a linker error. (See Header Files and Multiple Source Files for the one-definition rule.)

An inline static member is a declaration and a definition that may appear in many translation units; the linker merges them into one variable, just like an inline variable. It's the modern default: write the initializer in the class and you're done.

Static constants

For class-wide constants, use static constexpr. A constexpr static data member is implicitly inline since C++17, so it needs no separate definition either:

C++ Class constants with static constexpr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Because the values are constexpr, they can be used in static_assert, as array sizes and as template arguments. Older code uses static const int max = 10; (allowed in-class for integral types only) or an unnamed enum { max = 10 }; hack; prefer static constexpr.

Accessing static data

You can name a static member through the class (Ticket::issued(), Password::min_length) or through any object (a.issued()). Both reach the same variable. Prefer the class name: it tells the reader the value isn't per-object.

Static member functions

A static member function has no object, so:

  • it has no this pointer,
  • it can't read non-static members directly (whose health would it read?),
  • it can't be const, virtual or ref-qualified, since those all describe the object,
  • it can access private members of any object of its class that you pass to it, and private static members.
C++
class Player {
public:
    static int max_health() { return 100; }   // fine: no object needed
    static int health_of(const Player& p) {
        return p.health_;                     // fine: private access through a parameter
    }
    // static int bad() { return health_; }   // error: invalid use of member in static function
private:
    int health_ = 100;
};

A static member function is basically a free function that lives in the class's scope and has access to its private parts. When it doesn't need private access, a free function in a namespace is often the cleaner choice. Static functions shine in two places: helpers that conceptually belong to the type, and named constructors.

Named constructors (static factory functions)

Constructors can't have names, so two constructors taking a double would clash. A static function that returns an object solves this and makes call sites read clearly. Making the real constructor private forces everyone through the factories.

C++ Named constructors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Factories can also return std::optional, std::expected (as here; see std::optional, std::variant, std::any and std::expected) or std::unique_ptr when construction can fail or the concrete type varies. You'll use that last form in Abstract Classes and Interfaces.

Counting live objects

A classic exercise is a class that knows how many of its objects are alive. It shows a subtle point: every way of creating an object must increment the counter, including copies.

C++ Counting live objects, including copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

If you deleted the user-written copy constructor, the compiler-generated one would copy without incrementing, and the count would go negative as copies were destroyed. Keeping counters correct across copies and moves is one motivation for the rules in The Rule of Zero, Three and Five.

Static local variables vs static members

The word static means different things in different places, which confuses everyone at first:

Where Meaning
static data member one variable shared by the class
static member function belongs to the class, no this
static local variable in a function created once, on first use, and kept between calls
static at namespace scope internal linkage: visible only in this .cpp file (prefer an anonymous namespace)

A function-local static is initialized the first time control passes through its declaration, and since C++11 that initialization is thread-safe. That makes it handy for lazily built data. See Scope, Lifetime and Storage Duration for the full story.

The static initialization order problem

Static data members and globals defined in different .cpp files are initialized in an unspecified order. If the initializer of one uses another that hasn't been initialized yet, you read a zero or garbage value before main even starts. This is the "static initialization order fiasco".

The fixes:

  • Make the value constexpr (or constinit), so it is set at compile time and never depends on run-time order.
  • Wrap it in a function returning a reference to a function-local static, which is built on first use:
C++
const std::map<std::string, int>& default_limits() {
    static const std::map<std::string, int> limits{{"upload_mb", 50}, {"users", 10}};
    return limits;   // built the first time anyone asks, in a thread-safe way
}

Singletons and their problems

A singleton is a class that allows exactly one object and gives global access to it. The modern form ("Meyers singleton") uses the function-local static trick:

C++
class Logger {
public:
    static Logger& instance() {
        static Logger the_logger;     // created on first call, destroyed at exit
        return the_logger;
    }
    void log(std::string_view message) { std::println("[log] {}", message); }

    Logger(const Logger&) = delete;              // no copies
    Logger& operator=(const Logger&) = delete;
private:
    Logger() = default;                          // nobody else can construct one
};

// Anywhere in the program:
Logger::instance().log("started");

It's correct and thread-safe, and it is still usually a design smell:

  • It's a global variable in disguise. Any function can reach it, so dependencies are hidden and code becomes hard to reason about.
  • It's hard to test. You can't swap in a fake logger or a test database for one test.
  • "Exactly one" rarely stays true. Programs grow a second database connection, a second window, a per-thread cache.
  • Destruction order at exit is fragile. A singleton used from another static object's destructor may already be gone.

The usual alternative is plain dependency injection: create the object in main and pass a reference to the code that needs it. Keep singletons for things that are truly process-wide and stateless or nearly so. Design Patterns in C++ compares the options.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A class has inline static int count = 0; and its constructor does ++count;. After creating three objects, what is sizeof of one object affected by?

    A static data member is stored once, outside every object. It doesn't contribute to sizeof of the class.
  2. 2. Why can't a static member function read a non-static member like name_ directly?

    A static member function isn't called on an object. It can access members of objects you pass to it, but there is no implicit object.
  3. 3. A header declares static int limit; inside a class (no inline, no initializer) and no .cpp file defines it. Code that uses Config::limit fails at which stage?

    A non-inline static data member declared in the class is only a declaration. Without a definition in exactly one .cpp file, the linker can't find the variable. Writing inline static avoids the problem.
  4. 4. What is the main drawback of the singleton pattern?

    A function-local static singleton is thread-safe and needs no new. Its real cost is in the design, because global access hides dependencies and prevents substituting another object in tests.

Summary

  • A static data member has one copy for the whole class, stored outside every object, with static storage duration.
  • Write inline static T name = value; (C++17) or static constexpr T name = value; in the class; older code needs one out-of-class definition in a .cpp file.
  • Static member functions have no this, can't be const or virtual, and are called as Class::function().
  • Named constructors are static functions that build objects with clear names and can report failure with std::optional or std::expected.
  • Counters must handle every way objects are created, including copies.
  • Avoid initialization-order bugs with constexpr/constinit or function-local statics; treat singletons as globals and prefer passing dependencies explicitly.

Next: Friend Functions and Classes, where you'll let selected functions and classes see a class's private members.