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

source.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A {
public:
void funcA() {
return;
}

protected:
void funcB() {
return;
}

private:
void funcC() {
return;
}
};
translate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class A  /* size: 1, align: 1 */
{

public:
inline void funcA()
{
return;
}


protected:
inline void funcB()
{
return;
}


private:
inline void funcC()
{
return;
}

};

2. Out-of-Class Definition

If you define a function outside the class declaration, it is not inline by default.

source.cpp
1
2
3
4
5
6
7
8
9
class A {
void funcA(); // declaration
};


// definition
void A::funcA() {
return;
}
translate.cpp
1
2
3
4
5
6
7
8
9
10
11
class A  /* size: 1, align: 1 */
{
void funcA();

};


void A::funcA()
{
return;
}

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.

example.cpp
1
2
3
4
5
6
7
8
9
class A {
public:
inline void funcA(); // Explicitly inline
};

// Now it is inline
inline void A::funcA() {
return;
}

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

  1. Functions defined inside a class are implicitly inline.
  2. Functions defined outside a class are NOT inline unless explicitly marked inline.
  3. To enable inlining, either define inside the class or use inline in the definition.
Author

Joe Chu

Posted on

2025-01-30

Updated on

2025-01-30

Licensed under

Comments