C++ Inline functions


Example

A function declared inline may be defined in multiple translation units, provided that all definitions are identical. It also must be defined in every translation unit in which it is used. Therefore, inline functions should be defined in headers and there is no need to mention them in the implementation file.

The program will behave as though there is a single definition of the function.

foo.h:

#ifndef FOO_H
#define FOO_H
#include <iostream>
inline void foo() { std::cout << "foo"; }
void bar();
#endif

foo.cpp:

#include "foo.h"
void bar() {
    // more complicated definition
}

main.cpp:

#include "foo.h"
int main() {
    foo();
    bar();
}

In this example, the simpler function foo is defined inline in the header file while the more complicated function bar is not inline and is defined in the implementation file. Both the foo.cpp and main.cpp translation units contain definitions of foo, but this program is well-formed since foo is inline.

A function defined within a class definition (which may be a member function or a friend function) is implicitly inline. Therefore, if a class is defined in a header, member functions of the class may be defined within the class definition, even though the definitions may be included in multiple translation units:

// in foo.h
class Foo {
    void bar() { std::cout << "bar"; }
    void baz();
};

// in foo.cpp
void Foo::baz() {
   // definition
}

The function Foo::baz is defined out-of-line, so it is not an inline function, and must not be defined in the header.