skip to content

In C++, how do static data members and static member functions differ from non-static ones, and where must a static data member be defined?

level: middleimportance: should knowfreq 55%

answer

  1. one object per class
  2. no this pointer
  3. declaration versus definition
  4. C++17 inline variables
  5. odr-use needs a definition

basics

~20 s

A static data member is one object shared by the class, not part of each instance, and a static member function has no this. Since C++17, inline and constexpr static members are defined in the class; others need one namespace-scope definition.

solid answer

~50 s

A static data member is not a subobject: there is one copy for the whole program (one per thread if it is `thread_local`), and it exists even if no object is ever created. A static member function has no `this`, so it can use static members directly and instance members only through an object; it cannot be `const`, `volatile` or `virtual`. Both are still class members, so `private` and `protected` apply to them. Definition is the trap. Inside the class, a non-inline static data member is only declared, so it needs exactly one definition in a source file, such as `int Connection::open_ = 0;`. C++17 added `static inline int open_ = 0;`, a definition in the class, and made `static constexpr` members implicitly inline. A `static const int kMax = 64;` is still only a declaration, so odr-using it, for example binding it to the `const int&` parameter of `std::min`, fails at link time.

code

cpp · 20 lines
cpp
#include <cstdio>

class Connection {
public:
    Connection() { ++open_; }
    ~Connection() { --open_; }
    static int openCount() { return open_; }   // no this: callable without an object
    static constexpr int kMaxOpen = 8;          // constexpr static: implicitly inline
private:
    static inline int open_ = 0;                // C++17 inline variable: defined here
};

int main() {
    Connection a, b;
    {
        Connection c;
        std::printf("open=%d\n", Connection::openCount());
    }
    std::printf("open=%d of %d\n", Connection::openCount(), Connection::kMaxOpen);
}

go deeper

for a junior

Recall that a static data member is shared by all objects and that a static member function is called through the class name and has no this.

for a middle

Explain declaration versus definition, which forms are inline since C++17, and why odr-using a static const member can fail at link time.

for a senior

Diagnose the link error that appears only at -O0, and treat mutable static state as a global variable with thread-safety and test-isolation costs.

for a principal

Decide when class-level shared state is acceptable at all, and prefer constexpr constants and injected dependencies over mutable statics in a team's code.

## One object per class A **static data member** belongs to the class, not to an instance. The C++ standard says it is not part of the subobjects of a class: if it is not `thread_local` there is exactly one copy shared by all objects, and if it is `thread_local` there is one per thread. It has static storage duration, so it exists before and after any particular object, even if the program never creates one. When static objects are initialised and in what order is covered with storage duration. Typical uses: - **Counters and registries** shared by every instance, such as the number of open connections. - **Class-wide constants**, such as `static constexpr int kMaxOpen = 8;`. - **Shared resources** that each instance would otherwise duplicate. ## Static member functions have no this A **static member function** is called through the class name, `Connection::openCount()`, and receives no object. Consequences checked by the compiler: - It can read and write **static** members directly, and non-static members only through an object it is given. - It cannot be qualified with `const`, `volatile` or `virtual`, and it cannot carry a `&` or `&&` ref-qualifier, because all of those describe the object it does not have. - It can still access **private** members of any object of its class, because access control is granted per class. Apple clang 21 rejects the mistakes directly: ```plaintext staticerr.cpp:4:22: error: static member function cannot have 'const' qualifier staticerr.cpp:3:32: error: invalid use of member 'n' in static member function ``` ## Declaration versus definition The rule that trips people is that a declaration inside the class is not always a definition. The standard says the declaration of a **non-inline** static data member in its class definition is not a definition. | Form inside the class | Is it a definition? | Out-of-class definition needed? | |---|---|---| | `static int open_;` | no | yes, exactly one: `int Connection::open_ = 0;` | | `static const int kMax = 64;` | no, even with the initializer | yes, if `kMax` is odr-used | | `static constexpr int kMax = 64;` | yes since C++17 (implicitly inline) | no | | `static inline int open_ = 0;` | yes since C++17 | no | Before C++17 every static data member needed one out-of-class definition whenever it was odr-used, and writing that definition in a header that several translation units included broke the one-definition rule. C++17's **inline variables** let a header define the member once for the whole program; the linker merges the copies. Redeclaring a `static constexpr` member outside the class is still accepted but deprecated. ## The odr-use link error The middle row of the table is the classic surprise. Given `struct Limits { static const int kMax = 64; };`, using `Limits::kMax` as a constant value is fine, but passing it to `std::min(100, Limits::kMax)` binds it to a `const int&` parameter, which **odr-uses** it and so requires a definition. With `-std=c++17 -O0` Apple's linker reports: ```plaintext Undefined symbols for architecture arm64: "Limits::kMax", referenced from: ``` Optimised builds may inline the value and hide the error, which makes it look intermittent. The fixes, in order of preference: 1. Make it `static constexpr int kMax = 64;`, implicitly inline since C++17. 2. Make it `static inline const int kMax = 64;` when it is not a constant expression. 3. Add `const int Limits::kMax;` in exactly one source file, the pre-C++17 fix. ## Access and threads Static members obey `public`, `protected` and `private` like any member, so a private static counter can be read only through a public static function such as `openCount()`. Other points worth knowing: - A mutable static is effectively a **global variable** with a class-scoped name: concurrent writes from several threads race unless it is a `std::atomic` or protected by a lock. - Its value **leaks between tests** that run in one process, so a test that constructs connections changes what the next test observes. - A `static thread_local` data member gives each thread its own copy, which removes the race but also any sharing. - A const member function may modify a static data member, because the static is not part of `*this`. The counter in the code example is safe only because `main` is single-threaded; in a server it would be `static inline std::atomic<int> open_{0};`.

  • In C++, why does static const int kMax = 64; sometimes link and sometimes not?
    The in-class declaration is not a definition. Uses that only need the value, such as an array bound, never touch the symbol. An odr-use, such as binding `kMax` to a `const int&` parameter or taking its address, needs a definition, and without one the link fails. Optimisation can inline the value and hide the error. `static constexpr` or `static inline const` makes the declaration a definition in C++17.
  • Can a C++ static member function access private members of an object of its own class?
    Yes. Access control is checked per class, not per object, so a static member function such as a factory or a comparison helper can read the private members of any object of its class that it is given. What it lacks is an implicit object: it must name the object explicitly, because there is no `this`.

  • Each object gets its own copy of a static data member.
  • A static member function can be declared const to promise it changes nothing.
  • Since C++17 every static const data member is implicitly inline.
  • Static data members ignore private and protected access.
  • A static data member exists only after the first object is constructed.