September 29th, 2012, 11:12 PM
Noob Question on headers.
I have just finished many tutorials on C++ for beginners. And I have a lot of separate classes with individual topics. I am making a console application to launch them separately.
Question is, should I have one header file for each class I have?
So in the Main.h , i would #include all the other headers, and in the Main.cpp , i just include the Main.h. Is this how it should be done? Thanks in advance.
September 30th, 2012, 02:21 AM
> Question is, should I have one header file for each class I have?
You can normally do away with main.h. Each class typically has it's own .h and .cpp file.
In main.cpp, just have the #includes for
September 30th, 2012, 01:10 PM
The entire idea of header files is to provide to a source file (ie, a .cpp) macros (#define), type declarations, extern'd global variables, and function prototypes from another source file.
That is what you're doing by placing each class declaration in a header file. Every source file that uses that class declaration must include its header file, but if a source file does not use a class, then it does not need to include that header file. For example, Random.cpp must include Random.h, because it implements that class. If Pointer.cpp also uses the Random class, then it must also include Random.h, but if it doesn't use it then it won't (though including it won't hurt except to slow down compile time). If Main.cpp uses the Random class, then the same applies.
Only those source files that need to share information with other source files need to have a header file. What is in Main.h? Does it have type definitions that any of the other source files need? Does it have macros that the others need? Does it have the prototypes of functions in Main.cpp that the others need? Or are the only functions that Main.cpp contain main() itself, plus maybe a few other functions that are only called from main()? If Main.cpp has no information that the other source files need, then there is no need for Main.h.
BTW, it is generally a good practice to have one header file for each class. Though if a class is only used by one another class, it would make sense to place them both in the same header file and to place both of their implementations in the same source file. Whatever works best.