Why are C++ inline functions in the header?

thecoshman picture thecoshman · Feb 20, 2011 · Viewed 108.3k times · Source

NB This is not a question about how to use inline functions or how they work, more why they are done the way they are.

The declaration of a class member function does not need to define a function as inline, it is only the actual implementation of the function. For example, in the header file:

struct foo{
    void bar(); // no need to define this as inline
}

So why does the inline implementation of a classes function have to be in the header file? Why can't I put the inline function the .cpp file? If I were to try to put the inline definition in the .cpp file I would get an error along the lines of:

error LNK2019: unresolved external symbol 
"public: void __thiscall foo::bar(void)"
(?bar@foo@@QAEXXZ) referenced in function _main 
1>C:\Users\Me\Documents\Visual Studio 2012\Projects\inline\Debug\inline.exe 
: fatal error LNK1120: 1 unresolved externals

Answer

CB Bailey picture CB Bailey · Feb 20, 2011

The definition of an inline function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it.

The easiest way to achieve this is by putting the definition in a header file.

If you want to put the definition of a function in a single source file then you shouldn't declare it inline. A function not declared inline does not mean that the compiler cannot inline the function.

Whether you should declare a function inline or not is usually a choice that you should make based on which version of the one definition rules it makes most sense for you to follow; adding inline and then being restricted by the subsequent constraints makes little sense.