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
raja
Published on 28-May-2019 12:21:30
Advertisements