C++ Header Files, Code Separation

Parkman picture Parkman · Nov 11, 2008 · Viewed 30.7k times · Source

I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file. What I want to do now is convert this into separate files such that they contain similar code or whatnot. My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at?

Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation?

Any insight into methods or best practises would be great, thanks!

Answer

Martin York picture Martin York · Nov 11, 2008

Header files should contain class and function declarations.

Source files contain class and function definitions.

It is standard practice (i.e. read easier) to have one declaration per header file and one definition per source file, though for small (read simpler helper) objects you sometimes group them with related more substantial objects.

Example: Class Menu

Menu.h:     Contains the Menu declaration.
Menu.cpp:   Contains the Menu definition.

The reason header files contain the declarations is so that you can include them from multiple source files and thus each source file has exactly the same definition of each class and function.

Consider it this way:
If you did not have header files then you would need to have the class and/or function declarations (without) definitions in every source file, this means a copy of the same declaration in every file. Thus if you modify a class you need to make the same modification in every file. By the use of a header file you have the declaration in one place and thus only one object to modify.