How do inline variables work in C++/C++17?


In C++, we can use the inline keyword for functions. In C++ 17 version, the inline variable concept has come.

The inline variable is allowed to be defined in multiple translation units. It also follows the one definition rule. If this is defined more than one time, the compiler merges them all into a single object in final program.

In C++ (before C++17 version), we cannot initialize the value of static variables directly in the class. We have to define them outside of the class.

Example Code

#include<iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         ++num;
      }
      ~MyClass() {
         --num;
      }
      static int num;
};
int MyClass::num = 10;
int main() {
   cout<<"The static value is: " << MyClass::num;
}

Output

The static value is: 10
In C++17, we can initialize the static variables inside the class using inline variables.

Example Code

#include<iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         ++num;
      }
      ~MyClass() {
         --num;
      }
      inline static int num = 10;
};
int main() {
   cout<<"The static value is: " << MyClass::num;
}

Output

The static value is: 10

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements