Are there any differences whatever in these two approaches in the final compiled program or is it guaranteed to be the same?
Both are same.
Member functions defined inside the class/structure body are implicitly inline
.
However, in the first example the function can be inline
d in every translation unit where this header will be included. In second example the function can only be inlined in the cpp file which defines the function. This is because the compiler needs to see the defintion of a function at the point of function call to try and make it inline.
To answer the Q in comments:
Lets say you keep the definition of function marked as inline
in a cpp file A.cpp
and try to call this function from another cpp file, B.cpp
. You will end up getting an "undefined external symbol" error, this is because in C and C++ each translation unit is compiled separately and the definition of the function located in A.cpp
is not available while compiling B.cpp
.
While if the function is only called from A.cpp
in which it is defined then the definition is available in the same file and the compiler and linker are happy to compile and link to it.
C++03 7.1.2 Function specifiers:
Para 3:
A function defined within a class definition is an inline function. The inline specifier shall not appear on a block scope function declaration.
Which one should choose and why in terms of good coding practices/experience?
The class definition is to serve as an interface to the users of the class. The users of this interface do not need to see the implementation details of the functions. All they need to see is how to use this interface.By putting the function definition(a pretty long one as you mention) inside the class you provide unnecessary details to the users thereby making it difficult for them to see what they actually need to see.
The best way to go about this is:
- Declare the function in class definition without
inline
keyword &
- Put the function definition with keyword
inline
outside the class body.
Good Read:
With inline member functions that are defined outside the class, is it best to put the inline keyword next to the declaration within the class body, next to the definition outside the class body, or both?
AFAIK, most of the boost libs are header-only - why did they do choose to do that?
Most of Boost libraries are template libraries and for template based libraries the compiler needs to see the definitions at the point of usage and hence the template functions need to be inline.
Good Read:
Why can templates only be implemented in the header file?