Question:
Should you define functions directly in the .h
header file, or always define them in the .cpp
file?
Answer:
If the function will be used only within one CPP, then it makes little sense to put it into the header file. If functions call each other, then the declaration and implementation can be separated. Encapsulation type, "private function".
If the function will be used in several files, then it should be declared in H and implemented in CPP. Thus, the function will exist in a single copy and it can be used anywhere, simply by including the header file. Public interface type, "public function".
If the function is template (template) or inline (inline), then without options, you should place both the declaration and the implementation in the header file, because template functions are essentially text templates, and the compiler will not be able to "extract" them from the CPP.
If the declaration and definition of the inline function are not placed in the header file, then at the stage of assembly errors will appear that "the definition of the function was not found".
If a non-inline function is placed in a header file, errors about "multiple function definitions" may appear at the build stage if the header file is included in several modules.
In general, the question boils down to "whether to make the function inline". But whether to make it inline is already a question of execution performance versus the possibility of linking versus build speed.
See also When should I write the keyword 'inline' for a function / method?