C++
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.
Exercise 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.
Show example solution
#include <iostream>
class Player {
public:
inline static int count = 0;
Player() { count++; }
};
int main() {
Player p1;
Player p2;
std::cout << Player::count;
return 0;
}
Test yourself
-
Complete the inline static declaration
class Player { public: ____ int count = 0; };
Show answer
class Player { public: inline static int count = 0; };
-
Match each declaration to its feature
- 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
-
What is the advantage of inline static?
inline static int count = 0;
- Speeds up the method
- Makes it private
- Requires no outside definition
- Saves memory
Show answer
Requires no outside definition — inline static can be initialized in the class without an outside definition.
Next lesson: static_assert