Inline functions
In solving the C++ problem of a macro
with access to private class members, all
the problems associated with preprocessor macros were eliminated. This was done
by bringing the concept of macros under the control of the compiler where they
belong. C++ implements the macro as inline
function, which is a true
function in every sense. Any behavior you expect from an ordinary function, you
get from an inline function. The only difference is that an inline function is
expanded in place, like a preprocessor macro, so the overhead of the function
call is eliminated. Thus, you
should (almost) never use macros, only inline functions.
Any function defined within a class body
is automatically inline, but you can also make a non-class function inline by
preceding it with the inline keyword. However, for it to have any effect,
you must include the function body with the declaration, otherwise the compiler
will treat it as an ordinary function declaration. Thus,
inline int plusOne(int x);
has no effect at all other than declaring
the function (which may or may not get an inline definition sometime later). The
successful approach provides the function body:
inline int plusOne(int x) { return ++x; }
Notice that the compiler will check (as
it always does) for the proper use of the function argument list and return
value (performing any necessary conversions), something the preprocessor is
incapable of. Also, if you try to write the above as a preprocessor macro, you
get an unwanted side effect.
You’ll almost always want to put
inline definitions in a header
file. When the compiler sees
such a definition, it puts the function type (the signature combined with the
return value) and the function body in its symbol table. When you use the
function, the compiler checks to ensure the call is correct and the return value
is being used correctly, and then substitutes the function body for the function
call, thus eliminating the overhead. The inline code does occupy space, but if
the function is small, this can actually take less space than the code generated
to do an ordinary function call (pushing arguments on the stack and doing the
CALL).
An inline function in a header file has a
special status, since you must include the header file containing the function
and its definition in every file where the function is used, but you
don’t end up with multiple definition errors (however, the definition must
be identical in all places where the inline function is
included).