Generally, it belongs into the header if you expect performance gains by inlining of that function, the definition does not require inclusion of additional headers and it is not expected that it changes very often.
Ah that does make sense. Can you give me an example of what the inplementation source looks like? Sorry Im coming from Java and it didn't have any of this separation lol
The source file just has all the definitions. To use your example:
TestClass.hpp:
1 2 3 4 5 6 7 8 9
class TestClass
{
public:
void set_values(int x,int y);
private:
int x;
int y;
};
TestClass.cpp:
1 2 3 4 5 6 7
#include "TestClass.hpp"
void TestClass::set_values(int a, int b)
{
x = a;
y = b;
}
However, a simple setter such as this is a good candidate for being defined in the header (potential gains by inlining if it is called often, does not require inclusion of additional headers and will rarely change, if ever).
Isn't it if you define the function inside the class definition inlining is automatic?
It's implicitly inline, yes. Although that doesn't necessarily mean it will be actually inlined, the decision is always up to the compiler.
Can you still inline if Define in a separate file?
Depends on your toolset. Some modern compilers support link-time code generation (MSVC, GCC, ICC, clang).
When you enable it, it allows optimizations across translation units, including inlining of functions defined in a different translation unit.
However, in the absence of LTO, the traditional compile/link procedure generally doesn't allow for that.