CodeBlanks Logo Icon CodeBlanks

inline static

Learn in-class definition with C++17 inline static.

inline static (C++17)

C++17 introduced inline static, which lets a static member be initialized directly in the class body. No separate outside definition is needed: inline static int count = 0;.

This is ideal for header-only design; even if a header is included in multiple .cpp files, no definition clash (ODR violation) occurs. The inline keyword tells the compiler this definition may appear in multiple translation units. Now every type (not just integers) can be initialized inside the class.

When to use inline static?

inline static is especially useful for classes defined in a header file. With regular static members, the outside definition must go in a .cpp file; otherwise multiple files cause a definition clash.

inline static removes this limitation. Both integers and types like std::string can be initialized inside the class. For example, inline static std::string name = "game"; is valid. This makes writing header-only libraries easier in modern C++ projects.

Practice Add a counter with inline static

Define a Player class. Under public: add inline static int count = 0;. Increment count++ in the constructor. In main create two Player objects and write std::cout << Player::count;. Do NOT write an outside definition.

Starter code

main.cpp
#include <iostream>

// Define the Player class here

int main() {
    // Create two Players and print count
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Player {
public:
    inline static int count = 0;
    Player() { count++; }
};

int main() {
    Player p1;
    Player p2;
    std::cout << Player::count;
    return 0;
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the inline static declaration

Question
class Player { public: ____ int count = 0; };
Answer
class Player { public: inline static int count = 0; };

Explanation: inline static (C++17) requires no outside definition.

2 Match each declaration to its feature

Term Meaning
inline static int x = 0; C++17 in-class definition
static int x; Outside definition needed
static const int N = 5; Integral in-class
int Player::count = 0; Outside definition form

3 What is the advantage of inline static?

main.cpp
inline static int count = 0;
  • Speeds up the method
  • Makes it private
  • Requires no outside definition Correct answer
  • Saves memory

Explanation: inline static can be initialized in the class without an outside definition.

All lessons in Intermediate