I have question about write C++ code. I have seen some developer use
head only style (all class definition and implementation in .h file),
But others like to seperate the definition and implementation in h /
cpp file. Is this the style / favor only or there are some benefits to
use one vs the other?
Putting implementations in the header can greatly increase
dependencies. While you can declare functions that use objects
through reference or pointer without having full definitions, you
can't actually *use* them. Thus you'll need to include anything used
by your interface even if you could have otherwise avoided it.
Further, anything you use that's not exposed to the outside world
through your interface will also need to be included so it can be
used.
This can greatly increase compile times and also causes unnecessary
binding. Consider changing something in one of the functions your
class implements. If it's in the header then everything that includes
it must recompile as well. If it's in a .cpp file then only that
needs to recompile.
Yet further, if you implement your definitions in a .cpp file you can
leverage functions that you define within it. You can split complex
functionality into smaller functions without polluting your
interface. This is not possible if that definition is in a header
(these functions will be exposed as well).
Worse, you'll very often need to use a class that also has some sort
of dependency on the class you're currently working on. For example,
you might have some sort of parent/child relationship where the child
is contained in the parent and keeps a reference back. Perhaps some
child operations use the parent. In these cases you simply cannot do
everything in the header.
Yet even worse, if you're using Visual Studio and have not changed the
default settings you can run into serious problems when implementing
definitions in the header. Visual studio tries to figure out if a
header has changed enough to warrant recompilation of its clients
(those translation units that include it). It's not particularly good
at this though and often falls prey to false negatives, leaving
translation units using old definitions of a function. I've run into
this problem more times than I care to count.
In my opinion there's ample reason to place functions in .cpp files
and only declarations in headers whenever possible. You may be
tempted to implement some functions "inline", which requires the
definition in the header, but modern compilers are capable of inlining
across translation units. You may be tempted to implement "trivial"
functions in a header, but again in my opinion all functions should be
"trivial", with more complex functions simply using combinations of
trivial functions to do their job.
I definitely side on the .cpp file definitions even though I sometimes
get lazy and do otherwise. You'll live longer if you do.