Is it preferred to define inline methods like:
// math.h
class Math
{
public:
inline static int sum(int a, int b)
{
return a + b;
}
};
or
// math.h
class Math
{
public:
static int sum(int a, int b);
};
// math.cpp
inline int Math::sum(int a, int b);
{
return a + b;
}
and why? Is there any difference? Should you leave inlining entirely up to the compiler? (I know this is pretty subjective but I’d like to hear some opinions and reasons)
Also, I believe it is true that most compilers will inline or not inline of their own accord regardless of the presence or absence of the inline keyword?
Inlining is entirely up to the compiler. The
inlinekeyword, like the old Cregisterkeyword is a suggestion to the compiler to do some optimisation.However, compiler writers know so much more than we lesser beings about their target architectures that this is really unnecessary.
Because of that, I don’t ever use
inlineso the question is moot (for me) but I would prefer to keep all code out of headers since that always led to double-defined symbols in C compilers.Putting code in header files also leaks information unnecessarily. People using your headers should not be able to see the implementation details.