Class Functions inlining
Today, while reading a book by Bjarne Stroustrup, I came across an interesting C++ fact that I hadn’t known before.
1. Introduction
Functions defined in a class are implicitly considered as inline, regardless of whether it it is public, protected, or private(access specifier does not affect).
This can be verified through C++ Insights: https://cppinsights.io/s/1a8f7945
| 1 | class A { | 
| 1 | class A /* size: 1, align: 1 */ | 
2. Out-of-Class Definition
If you define a function outside the class declaration, it is not inline by default.
| 1 | class A { | 
| 1 | class A /* size: 1, align: 1 */ | 
Most of the time, in our project, we separate declarations and definitions into .cpp and .h files. In such case, functions are not inlined by default.
To make out-of-class definition inline, we need to use inline keyword explicitly.
| 1 | class A { | 
3. Link-Time Optimization (LTO)
Modern compiler optimize function calls automatically using advanced strategies such as Link-Time Optimization(LTO).
LTO enables cross-translation-unit optimizations, allowing functions defined in .cpp files to be inlined when beneficial.
To enable LTO, we can add a flag -flto to the build command when using GCC/Clang compilers.
4. Conclusion
- Functions defined inside a class are implicitly inline.
- Functions defined outside a class are NOT inline unless explicitly marked inline.
- To enable inlining, either define inside the class or use inline in the definition.
Class Functions inlining
