I've been taught to keep class definitions and code separate.
However, I've seen situations where people would often include some bits of code in the header, e.g. simple access methods which returns a reference of a variable.
Where do you draw the line?
So to avoid this problem, you can create your header file, and can use it whenever you require. First of all, create a header file, and for that, you will write your code in the file, and save it with the . h extension, for example, fname. h.
In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”.
A header file should be included only when a forward declaration would not do the job. The header file should be so designed that the order of header file inclusion is not important. The header file inclusion mechanism should be tolerant to duplicate header file inclusions.
the header file (. h) should be for declarations of classes, structs and its methods, prototypes, etc. The implementation of those objects are made in cpp.
Generally speaking, things you want the compiler to inline, or templated code. In either case, the code must be available to the compiler everywhere it's used, so you have no choice.
However, note that the more code you put in a header file, the longer it will take to compile - and the more often you'll end up touching header files, thus causing a chain reaction of slow builds :)
One reason to minimize the amount of code in headers is to minimize the amount of code to be recompiled when the implementation changes. If you don't care about that you can have any amount of code in headers.
Sometimes having the code in headers only is done intentionally to expose the code - ATL does that for eaxmple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With