I'm a beginner in C++, and I was wondering if it is best practice to define a member function directly in a class, such as:
// something.hpp
class C {
inline int func() { return ... ; }
}
rather than the usual:
// something.hpp
class C {
int func();
}
// something.cpp
int C::func() { return ... ; }
In my reading of Stroustrup's "The C++ Programming Language", I have seen him use either technique. Alas, I am confused as to whether it is good to do so in real-world applications and, in particular, the creation of libraries.
Best Answer
When a function is defined as part of the class definition, it is implicitly
inline
(regardless of whether you use that keyword). This has a number of consequences.Whether the function is defined as part of the class definition, or as an inline function outside of the class definition but still within the header is equivalent:
Now when we put the function definition into a separate compilation unit, we have a different set of consequences:
The large practical difference is what happens when you modify this function.
On large projects, avoiding recompilation is very important in order to enable fast feedback when making changes. This leads to various strategies:
However, inline functions still have their uses:
If you want to enable inlining optimizations within a compilation unit, declaring it as inline is not necessary or appropriate. It is more important that the function has “internal linkage”. For example, free functions (that are not class members) have internal linkage when declared
static
. The contents of an anonymous namespace have internal linkage. This is useful for helpers within a .cpp file.If performance and compilation times and ABI stability are no concern, then defining your functions as part of the class definition is perfectly fine. This is the case in many smaller projects that are internally used libraries or executables. Some people prefer having the function definitions right in the class. Other people prefer keeping the definitions separate, so that it's easier to get an overview of all members of the class.
This answer applies to all versions of the C++ standard, with the caveat that the C++ 20 module system changes this. If a function is defined within a class definition that is part of a module, it will not be considered inline.