The main language difference between an inline and a non-inline function is that inline functions are exempt from the one-definition rule, provided all definitions are the same.
This is a crucial feature for C++, since it allows you to write member function definitions inside class definitions and still be able to include the class definition in a header file.
Consider this header:
// stupid.h
#ifndef H_STUPID
#define H_STUPID
int foo() { return 8; }
#endif
stupid.h is not usable if you have to include it more than once, because you'll end up with multiple definitions of foo
. Making the declaration inline
lets you get around this problem. Applying the same logic to a class definition (remember that all member functions that are defined inline are implicitly declared inline
), this allows us to write this:
// works.h
#ifndef H_WORKS
#define H_WORKS
class Foo
{
int n;
public:
void f() { n *= 2; } // implicitly inline!
int g() const { return n; } // ditto
};
#endif
We can include works.h in as many translation units as we like, and there's no "multiple definition" error for Foo::f
and Foo::g
, because those are (implicitly) declared inline.
Of course inline
also serves as a hint to the compiler to replace function calls by copies of the function body, but the compiler can choose to do or not do that pretty much independent of whether or not you declare a function inline
.