Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: When is it acceptable to have code in the header file?

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?

like image 962
John Jiang Avatar asked May 20 '09 05:05

John Jiang


People also ask

Can you put code in header files?

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.

Which is the valid way to include header file in C?

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”.

When Should header files be used?

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.

What should be included in header file?

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.


2 Answers

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 :)

like image 139
bdonlan Avatar answered Oct 20 '22 17:10

bdonlan


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.

like image 35
sharptooth Avatar answered Oct 20 '22 18:10

sharptooth