Inline Variable in C++

Level 5499 keystrokes

Since C++17, inline static members can be initialized directly inside the class, even for types like string and vector, with no separate definition in a .cpp file. printConfig() prints them, and they can also be accessed as Config::version.

C++ code

1class Config {
2public:
// inline static: initialized in the class, no separate definition needed
3 inline static const string version = "1.0.0";
// A constant known at compile time
4 inline static constexpr int maxConnections = 100;
// Works for class types such as vector too
5 inline static const vector<string> supportedFormats = {"json", "xml", "csv"};
6
// Static function: can be called without an object
7 static void printConfig() {
8 cout << "Version: " << version << endl;
9 cout << "Max connections: " << maxConnections << endl;
10 cout << "Formats: ";
// Prints each format followed by a space
11 for (const auto& fmt : supportedFormats) cout << fmt << " ";
12 cout << endl;
13 }
14};
15
// Prints version, maximum connections and formats
16Config::printConfig();
// Accessed through the class name: prints "Direct access: 1.0.0"
17cout << "Direct access: " << Config::version << endl;

Output

Version: 1.0.0
Max connections: 100
Formats: json xml csv 
Direct access: 1.0.0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 27
  • "× 18
  • ;× 11
  • :× 10
  • (× 3
  • )× 3
  • {× 3
  • }× 3
  • =× 3
  • ,× 2

More C++ examples at level 5

← C++ typing practice