Inline Functions
An inline function is a function marked with the inline keyword or defined inside a class body.
Historically, inline suggested that the compiler could replace the function call with the function body.
Modern important meaning:
inline helps allow the same function definition in multiple translation units without violating the one-definition rule.
Function Defined Inside Class
Member functions defined inside the class body are implicitly inline.
#include <iostream>
using namespace std;
class Square {
private:
int side;
public:
explicit Square(int s) : side(s) {}
int area() const {
return side * side;
}
};
int main() {
Square square(5);
cout << square.area() << endl;
return 0;
}
Output:
25
Explicit Inline Function
inline int cube(int x) {
return x * x * x;
}
Important Truth
inline is not a command that forces the compiler to inline the function for speed.
The compiler may ignore the optimization request.
Small functions are good candidates. Large functions with loops or complex logic are poor candidates.
Viva Answer
An inline function is a function that can be defined in multiple translation units safely and may be expanded at the call site by the compiler. Functions defined inside a class body are implicitly inline. The compiler is not forced to inline the function for optimization.
Quick Check
- Are functions defined inside a class body implicitly inline?
- Does
inlineforce optimization? - Why should large functions usually not be treated as inline candidates?