- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements